Managing a singleton destructor

后端 未结 6 1745
眼角桃花
眼角桃花 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:45

    The first question is: do you want the singleton to be destructed. Destructing a singleton can lead to order of destruction problems; and since you're shutting down, the destructor can't be necessary to maintain program invariants. About the only time you want to run the destructor of a singleton is if it manages resources that the system won't automatically clean up, like temporary files. Otherwise, it's better policy to not call the destructor on it.

    Given that, if you want the destructor to be called, there are two alternatives: declare the single object as a static local variable in the instance function, or use std::auto_ptr or something similar, instead of a raw pointer, as the pointer to it.

提交回复
热议问题