我按照以下方式编写单例c ++:
class A {
private:
static A* m_pA;
A();
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL)
m_pA = new A();
return m_pA;
}
A::~A() {
FreeInstance() // Can I write this? are there any potential error?
}
void A::FreeInstance() {
delete m_pA;
m_pA = NULL;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!Evan Teran和sep61.myopenid.com的回答是正确的,非常好!我的方式是错的,我希望任何人写这样的代码都可以避免我的愚蠢错误.
我的项目中的单例A有一个智能指针向量,另一个线程也可以编辑这个向量,所以当应用程序关闭时,即使我添加了很多CMutex,它总是变得不稳定.多线程错误+单身错误浪费了我一天.
// ------------------------------------------------ -----------新单例,如果您认为以下示例中存在任何问题,欢迎您进行编辑:
class A {
private:
static A* m_pA;
explicit A();
void …Run Code Online (Sandbox Code Playgroud)