C++单例模式实现
test.h
#pragma once
class CSingleInstance
{
public:
static CSingleInstance* GetInstance();
private:
CSingleInstance();
CSingleInstance(CSingleInstance& ss){};
CSingleInstance& operator=(CSingleInstance& ss){};
~CSingleInstance();
static CSingleInstance* pInstance;//仅仅申明未定义
};
test.cpp
#include "test.h"
#include <iostream>
CSingleInstance* CSingleInstance::pInstance = NULL;
CSingleInstance* CSingleInstance::GetInstance()
{
if (!pInstance)pInstance = new CSingleInstance;
return pInstance;
}
CSingleInstance::CSingleInstance() {
std::cout << "instance create" << std::endl;
}
CSingleInstance::~CSingleInstance() {
std::cout << "instance destory" << std::endl;
}
main.cpp
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
CSingleInstance* a = CSingleInstance::GetInstance();
CSingleInstance* b = CSingleInstance::GetInstance();
cout << a << endl;
cout<< b <<endl;
}
执行结果
instance create
013CB5D0
013CB5D0
可以看到析构函数并未被调用
解决:
test.h
#pragma once
class CSingleInstance
{
public:
static CSingleInstance* GetInstance();
private:
CSingleInstance();
CSingleInstance(CSingleInstance& ss){};
CSingleInstance& operator=(CSingleInstance& ss){};
~CSingleInstance();
static CSingleInstance* pInstance;//仅仅申明未定义
class CHelper {
public:
CHelper();
~CHelper();
};
static CHelper helper;//未定义
};
test.cpp
#include "test.h"
#include <iostream>
CSingleInstance* CSingleInstance::pInstance = NULL;
CSingleInstance::CHelper CSingleInstance::helper;
CSingleInstance* CSingleInstance::GetInstance()
{
if (!pInstance)pInstance = new CSingleInstance;
return pInstance;
}
CSingleInstance::CSingleInstance() {
std::cout << "instance create" << std::endl;
}
CSingleInstance::~CSingleInstance() {
std::cout << "instance destory" << std::endl;
}
CSingleInstance::CHelper::CHelper()
{
GetInstance();
}
CSingleInstance::CHelper::~CHelper()
{
if (pInstance) {
CSingleInstance* tmp = pInstance;
pInstance = NULL;
delete tmp;
}
}