问题描述
我按照以下方式编写单例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()//我可以写这个吗?有什么潜在的错误?
}
void A :: FreeInstance(){
delete m_pA;
m_pA = NULL;
}
谢谢! Evan Teran和sep61.myopenid.com的答案是对的,真的很好!
我的方式是错的,我希望任何一个写这样的代码可以避免我的愚蠢的错误。
我的单例在我的项目中有一个智能指针的向量,而另一个线程也可以编辑这个向量,所以当应用程序关闭时,它总是变得不稳定,即使我添加了大量的CMutex。多线程错误+单例错误浪费我1天。
// ------------------------------- ----------------------------
一个新的单例,如果你认为有任何问题,欢迎你编辑以下示例:
class A {
private:
static A * m_pA;
explicit A();
void A(const A& a);
void A(A& a);
const A& operator =(const A& a);
virtual〜A();
public:
static A * GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A * A :: GetInstance(){
if(m_pA == NULL){
static A self;
m_pA =& self;
}
return m_pA;
}
A ::〜A(){
}
<$> c $ c> if(m_pA == 0){
static A static_instance;
m_pA =& static_instance;
}
I write a singleton c++ in the follow way:
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;
}
Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good!My way is wrong, I wish any one writting such code can avoid my silly mistake.
My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.
//-----------------------------------------------------------A new singleton, you are welcome to edit if you think there is any problem in the following sample:
class A {
private:
static A* m_pA;
explicit A();
void A(const A& a);
void A(A &a);
const A& operator=(const A& a);
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL){
static A self;
m_pA = &self;
}
return m_pA;
}
A::~A() {
}
You can avoid needing to delete it by using a static object like this:
if(m_pA == 0) {
static A static_instance;
m_pA = &static_instance;
}
这篇关于任何人都可以提供一个样例的Singleton在c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!