今天要写一个C++的singleton模式的类,开始参考网上其他兄弟写的类,发现不能删除客户端创建出来的指针,又经过一翻研究总结如下,
1.构造函数 析构函数 要声明private: 不让客户端实例化此类(例如: DXHelper helper; DXHelper *pHelper = new DXHelper() 都是禁止的)
2.不能进行赋值或者拷贝构造操作。 //声明copy和赋值 操作重载函数为private并且没有实现。
3. 只能通过本类提供的GetInstance函数得到类的实力 并且调用其成员
4.在GetInstance()中定义局部变量 这样能自动销毁,不存在内存泄漏问题
#pragma once
// include directx9
#include <d3d9.h>
class DXHelper
{
public:
static DXHelper &GetInstance()
{
static DXHelper instance; \\ 局部变量 自动销毁, 不存在内存泄漏问题
return instance;
}
private:
DXHelper()
{
// set the constructor is private so that the client can‘t instance this class directly
}
~DXHelper(void)
{
}
DXHelper(const DXHelper&) ;// Prevent clients from copying a Singleton
DXHelper& operator=(const DXHelper&) ;;// Prevent clients from assignment
Public:
void DoSomething();
};
客户端代码:
DXHelper::GetInstance().DoSomething(); // 只能通过此种方法调用,其他一切方便都会出现编译错误。。