C++建立对象
只在堆上创建对象
#include <iostream>
using namespace std;
class HeapOnly
{
public:
static HeapOnly* Create(){
return new HeapOnly;
}
static void Destory(HeapOnly* ptr){
delete ptr;
ptr = nullptr;
}
protected:
HeapOnly(){}
HeapOnly(const HeapOnly&);
//C++11写法
//HeapOnly(const HeapOnly&) = delete;
~HeapOnly(){}
};
int main()
{
HeapOnly* object = HeapOnly::Create();
HeapOnly::Destory(object);
return 0;
}
#include <iostream>
using namespace std;
class HeapOnly
{
public:
static HeapOnly* Create(){
return new HeapOnly;
}
protected:
HeapOnly(){}
HeapOnly(const HeapOnly&);
//HeapOnly(const HeapOnly&) = delete;
};
int main()
{
HeapOnly* object = HeapOnly::Create();
delete object;
return 0;
}
#include <iostream>
using namespace std;
class HeapOnly
{
public:
static void Destory(HeapOnly* ptr){
delete ptr;
ptr = nullptr;
}
protected:
~HeapOnly(){}
};
int main()
{
HeapOnly* object = new HeapOnly;
HeapOnly::Destory(object);
return 0;
}
将operator new和operator delete权限设为private
#include <iostream>
using namespace std;
class StackOnly
{
public:
StackOnly(){}
~StackOnly(){}
private:
void* operator new(size_t szie);
void operator delete(void* ptr);
};
int main()
{
StackOnly a;
return 0;
}
单例模式
一个类只能创建一个对象,保证系统中该类只有一个实例,并提供它的全局访问点,该实例被所有程序模块共享
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance(){
return _instance;
}
private:
Singleton(){}
Singleton(const Singleton&);
Singleton& operator=(Singleton const&);
//Singleton(const Singleton&) = delete;
//Singleton& operator = (Singleton const&) = delete;
static Singleton* _instance;
};
//在入口程序前完成单例对象的初始化
Singleton* Singleton::_instance = new Singleton;
int main()
{
cout << Singleton::GetInstance << endl;
cout << Singleton::GetInstance << endl;
return 0;
}
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance(){
//使用Double-Check的方式加锁,保证效率和线程安全
if (_pInstance == nullptr){
_mtx.lock();
if (_pInstance == nullptr)
_pInstance = new Singleton;
_mtx.unlock();
}
return _pInstance;
}
//实现一个垃圾回收类
class CGarbo{
public:
~CGarbo(){
if (Singleton::_pInstance)
delete Singleton::_pInstance;
}
};
//定义一个静态成员变量,程序结束时系统自动调用它的析构函数,从而释放单例对象
static CGarbo Garbo;
private:
Singleton(){}
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
static Singleton* _pInstance;
static mutex _mtx;
};
Singleton* Singleton::_pInstance = nullptr;
Singleton::CGarbo Singleton::Garbo;
mutex Singleton::_mtx;
void func(int n){
cout << Singleton::GetInstance() << endl;
}
int main()
{
//多线程环境测试
thread t1(func, 10);
thread t2(func, 10);
t1.join();
t2.join();
cout << Singleton::GetInstance << endl;
cout << Singleton::GetInstance << endl;
return 0;
}