Managing a singleton destructor

后端 未结 6 1735
眼角桃花
眼角桃花 2020-12-18 04:08

The following small example implements a singleton pattern that I\'ve seen many times:

#include 

class SingletonTest {
private:
  Singleton         


        
6条回答
  •  执念已碎
    2020-12-18 04:41

    You could always friend the shared_ptr (or rather scoped_ptr, which is more fitting) to allow it access to your private destructor.

    Note that there's also the system atexit() function which can register a function to call at the end of the application. You could pass a static function of your singleton that just does delete instanance; to it.

    Note that it's usually a good idea separates the class that is to be a singleton from the singleton-ness of it. Especially for testing and/or when you do need the doubleton. :)

    While I'm at it, try to avoid lazy initialization. Initialize/create your singletons at startup, in a well determined order. This allows them to shut down properly and resolves dependencies without surprises. (I have had cyclic singleton hell... it's easier than you think...)

提交回复
热议问题