class Single
{
private:
Single(){}
public:
static Single
* GetInstance()
{
if (my_instance
== nullptr)
{
my_instance
= new Single();
static DeleteObj d1
;
}
return my_instance
;
}
class DeleteObj
{
public:
~DeleteObj()
{
if (Single
::my_instance
)
{
delete Single
::my_instance
;
Single
::my_instance
= nullptr;
cout
<< "析构" << endl
;
}
}
};
void func()
{
cout
<< "this is a public func" << endl
;
}
private:
static Single
*my_instance
;
};
Single
* Single
::my_instance
= NULL;
int main()
{
Single
* p_a
= Single
::GetInstance();
Single
* p_b
= Single
::GetInstance();
if (p_a
== p_b
)
cout
<< "this is a identical obj" << endl
;
return 0;
}
std::call_once使用
std::call_once(),C++11引入的函数,该函数第二个参数是一个函数名 call_once()保证函数只被调用一次,具备互斥量能力,比互斥量更高效 与一个标记结合使用: std::once_flag
static void CreateInstance()
{
my_instance
= new Single();
static DeleteObj d1
;
}
static Single
* GetInstance()
{
std
::call_once(flag
,CreateInstance
);
return my_instance
;
}
转载请注明原文地址: https://mac.8miu.com/read-486903.html