管理单例析构函数 [英] Managing a singleton destructor

查看:93
本文介绍了管理单例析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下小例子实现了我已经看过很多次的单例模式:

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

#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;
}

我遇到的主要问题是我的单例析构函数

The main problem I have with this is that the destructor of my singleton is never called.

我可以让实例 a(c ++ 0x?) shared_ptr

I can instead make instance a (c++0x?) shared_ptr, which works well - except that it means my destructor has to be public.

我可以添加一个静态的cleanup方法,但打开提高用户错误的可能性(即忘记调用它)。它也不允许在(未处理)异常面前进行适当的清理。

I could add a static 'cleanup' method but that opens up the possibility of user error (i.e. forgetting to call it). It would also not allow for proper cleanup in the face of (unhandled) exceptions.

有一个常见的策略/模式将允许延迟实例化,'自动'调用我的析构函数,仍然允许我保持析构函数私有?

Is there a common strategy/pattern that will allow lazy instantiation, 'automatically' call my destructor, and still allow me to keep the destructor private?

推荐答案

...不是一个直接的答案,一个注释 - 为什么不这样做singleton:

...not exactly a direct answer, but too long for a comment - why not do the singleton this way:

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

public:
  static SingletonTest& get_instance()  {
    static SingletonTest instance;
    return instance;
  }
};

现在你有一个懒惰的单例,将在退出时被破坏...。比您的代码...

Now you have a lazy singleton that will be destructed on exit... It's not any less re-entrant than your code...

这篇关于管理单例析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆