Example of c++ singleton pattern

  • What language is this for? C++
  • Which rule?
    a combination of
    cpp:S6018 - Use inline variables to declare this global variable
    cpp:S5421 - Global variables should be const.

Why do you believe it’s a false-positive/false-negative?
i don’t know how to create a singleton that has a private destructor

  • SonarQube - LTS version 9.9?

For example how to create a simple singleton struct like below that meets sonarqube c++ rules?

struct DeviceData {
 // have to make it a singleton so that the WndProc method can access it
static auto Get() -> auto& {
  static DeviceData singleton;
  return singleton;
}

// Just some plain pointers
ID3D11Device* g_pd3dDevice{nullptr};
ID3D11DeviceContext* g_pd3dDeviceContext{nullptr};
IDXGISwapChain* g_pSwapChain{nullptr};
ID3D11RenderTargetView* g_mainRenderTargetView{nullptr};

private:
DeviceData() = default;
 };

1 Like

Hello @Matthieu_Bolt,

Indeed, in your case, the rule “S6018 - Use inline variables to declare this global variable” does not make sense: if you make your singleton inline, the code will not compile because the type DeviceData is incomplete.
Your code snippet seems correct: it’s the most common and acknowledged way to create singletons (in rare cases where they are needed).
I have created a ticket (CPP-4342) to fix this.

Thank you for your input.
Have a nice day,

Amélie