我正在多线程环境中创建一个单例类,任何线程都可以删除单例对象。我想保护这个。我在某处读到可以避免这个问题,我们可以将析构函数设为私有(private)并提供销毁方法。我们该怎么做?示例代码将有所帮助..
提前致谢。
最佳答案
class Singleton; // forward declaration
Singleton * s = NULL; // global object available to all threads
// Place this class in a location unavailable to all threads except Main thread
class ManageSingleton
{
public:
static void DestroySingleton(Singleton * s)
{
delete s;
}
}
class Singleton
{
friend class ManageSingleton;
protected:
~Singleton() {}
};
void main()
{
s = new Singleton;
while (...)
{
// other threads access Singleton object until program is finished
}
// Program is now finished; destroy Singleton object
ManageSingleton::DestroySingleton(s);
}
关于c++ - 在 Singleton 设计模式的情况下,我们如何使析构函数私有(private)化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10185644/