Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
URL Rewriter Bot
URL Rewriter Bot

@Loki Astari's answer@Loki Astari's answer is excellent.

However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.

In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:

class Singleton { public: Singleton(Singleton const&) = delete; Singleton& operator=(Singleton const&) = delete; static std::shared_ptr<Singleton> instance() { static std::shared_ptr<Singleton> s{new Singleton}; return s; } private: Singleton() {} }; 

@Loki Astari's answer is excellent.

However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.

In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:

class Singleton { public: Singleton(Singleton const&) = delete; Singleton& operator=(Singleton const&) = delete; static std::shared_ptr<Singleton> instance() { static std::shared_ptr<Singleton> s{new Singleton}; return s; } private: Singleton() {} }; 

@Loki Astari's answer is excellent.

However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.

In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:

class Singleton { public: Singleton(Singleton const&) = delete; Singleton& operator=(Singleton const&) = delete; static std::shared_ptr<Singleton> instance() { static std::shared_ptr<Singleton> s{new Singleton}; return s; } private: Singleton() {} }; 
Source Link
Galik
  • 49k
  • 5
  • 85
  • 126

@Loki Astari's answer is excellent.

However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.

In this case std::shared_ptr can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:

class Singleton { public: Singleton(Singleton const&) = delete; Singleton& operator=(Singleton const&) = delete; static std::shared_ptr<Singleton> instance() { static std::shared_ptr<Singleton> s{new Singleton}; return s; } private: Singleton() {} };