C ++ Singleton设计模式

不羁岁月 提交于 2020-08-14 16:25:08

问题:

Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. 最近,我碰到了C ++的Singleton设计模式的实现/实现。 It has looked like this (I have adopted it from the real life example): 它看起来像这样(我从现实生活的示例中采用了它):

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

From this declaration I can deduce that the instance field is initiated on the heap. 从该声明中,我可以推断出实例字段是在堆上初始化的。 That means there is a memory allocation. 这意味着存在内存分配。 What is completely unclear for me is when exactly the memory is going to be deallocated? 对我来说,完全不清楚的是何时确切地将要释放内存? Or is there a bug and memory leak? 还是有错误和内存泄漏? It seems like there is a problem in the implementation. 似乎实现中存在问题。

My main question is, how do I implement it in the right way? 我的主要问题是,如何以正确的方式实施它?


解决方案:

参考一: https://stackoom.com/question/4EEN/C-Singleton设计模式
参考二: https://oldbug.net/q/4EEN/C-Singleton-design-pattern
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!