最近,我碰到了C ++的Singleton设计模式的实现/实现。它看起来像这样(我从现实生活的示例中采用了它):
// a lot of methods are omitted here class Singleton { public: static Singleton* getInstance( ); ~Singleton( ); private: Singleton( ); static Singleton* instance; };
从该声明中,我可以推断出实例字段是在堆上初始化的。这意味着存在内存分配。对我来说,完全不清楚的是何时确切地将要释放内存?还是有错误和内存泄漏?似乎实现中存在问题。
我的主要问题是,如何以正确的方式实施它?
在2008年,我提供了Singleton设计模式的C ++ 98实现,该模式是延迟评估,保证销毁,技术上不是线程安全的。
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 };
Dobbs博士:C ++和双重检查锁定的风险:第一部分