C 单例设计模式

新手上路,请多包涵

最近,我遇到了 C++ 单例设计模式的实现/实现。它看起来像这样(我从现实生活的例子中采用了它):

 // a lot of methods are omitted here
class Singleton
{
   public:
       static Singleton* getInstance( );
       ~Singleton( );
   private:
       Singleton( );
       static Singleton* instance;
};

从这个声明中,我可以推断出实例字段是在堆上启动的。这意味着有内存分配。对我来说完全不清楚的是何时释放内存?还是有错误和内存泄漏?执行起来好像有问题。

我的主要问题是,如何以正确的方式实施它?

原文由 Artem Barger 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 560
2 个回答

2008 年,我提供了单例设计模式的 C++98 实现,它是惰性求值、保证破坏、非技术线程安全的:

任何人都可以为我提供 C++ 中的 Singleton 示例吗?

这是 Singleton 设计模式的更新 C++11 实现,它是惰性求值、正确销毁和 线程安全的

 class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Don't forget to declare these two. You want to make sure they
        // are inaccessible(especially from outside), otherwise, you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};

请参阅这篇关于何时使用单例的文章:(不经常)

单例:应该如何使用

请参阅这两篇关于初始化顺序以及如何应对的文章:

静态变量初始化顺序

查找 C++ 静态初始化顺序问题

请参阅描述生命周期的这篇文章:

C++ 函数中静态变量的生命周期是多少?

请参阅这篇讨论单例的一些线程含义的文章:

单例实例声明为 GetInstance 方法的静态变量,它是线程安全的吗?

请参阅这篇解释为什么双重检查锁定在 C++ 上不起作用的文章:

C++ 程序员应该了解哪些常见的未定义行为?

Dobbs 博士:C++ 和双重检查锁定的危险:第一部分

原文由 Martin York 发布,翻译遵循 CC BY-SA 4.0 许可协议

它将类的实例化限制为一个对象。当需要一个对象来协调整个系统的动作时,这很有用

class Singleton {
private:
    int data;
    static Singleton* instance;
    Singleton();
public:
    static Singleton* getInstance();
};
Singleton* Singleton::instance = 0;
Singleton::Singleton()
{
    this->data = 0;
    cout << "constructor called.." << endl;
}



Singleton* Singleton::getInstance() {
    if (!instance) {
        instance = new Singleton();
        return instance;
    }
}
int main() {
    Singleton *s = s->getInstance();
    Singleton *s1 =s1->getInstance();
    }

原文由 Sarath Govind 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题