管理单例析构函数

sje*_*397 6 c++ c++11

以下小例子实现了我多次见过的单例模式:

#include <iostream>

class SingletonTest {
private:
  SingletonTest() {}
  static SingletonTest *instance;
  ~SingletonTest() {
    std::cout << "Destructing!!" << std::endl;
  }

public:
  static SingletonTest *get_instance()  {
    if(!instance) instance = new SingletonTest;
    return instance;
  }
};

SingletonTest *SingletonTest::instance = 0;

int main(int argc, char *argv[]) {
  SingletonTest *s = SingletonTest::get_instance();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我遇到的主要问题是我的单身人士的析构函数从未被调用过.

我可以改为instance(c ++ 0x?)shared_ptr,这很好用 - 除了它意味着我的析构函数必须公开.

我可以添加一个静态的'清理'方法,但这会打开用户错误的可能性(即忘记调用它).面对(未处理的)例外,它也不允许适当的清理.

是否存在允许延迟实例化的常见策略/模式,"自动"调用我的析构函数,并且仍然允许我将析构函数保密?

Nim*_*Nim 20

...不是一个直接的答案,但是评论太长了 - 为什么不这样做单身人士:

class SingletonTest {
private:
  SingletonTest() {}
  ~SingletonTest() {
    std::cout << "Destructing!!" << std::endl;
  }

public:
  static SingletonTest& get_instance()  {
    static SingletonTest instance;
    return instance;
  }
};
Run Code Online (Sandbox Code Playgroud)

现在你有一个懒惰的单身人士将在退出时被破坏......它不会比你的代码重入...

  • @Antonio-怎么样?(我的意思是它如何避免多线程初始化的问题,以上不是线程安全的). (2认同)
  • @Antonio:它在C++ 03中是非标准的,但仅仅是因为C++ 03 Standard没有提到线程.任何体面的编译器都已经使这个线程安全.如果方法是内联的(并且没有在.cpp文件中定义),我在Windows(DLL)上遇到了这个习惯用法的问题,因为每个DLL都有自己的本地静态变量......虽然它是VC++ 03所以可能已经改变了. (2认同)