栈上:
class stack_class {
public:
stack_class(){}
~stack_class(){}
private:
void* operator new(size_t n) {
}
void operator delete(void * ptr) {
}
};
堆上:
class heap_class {
public:
static heap_class* create_heap_c() {
return new heap_class();
}
void destory() {
delete this;
}
private:
heap_class(){}
~heap_class(){}
};
饿汉:
class Singleton
{
private:
static Singleton* local_instance;
Singleton() {
cout << "构造" << endl;
};
~Singleton() {
cout << "析构" << endl;
}
public:
static Singleton* getInstance()
{
static Singleton locla_instance;
return &locla_instance;
}
};
懒汉:
class bh {
private:
static bh* _sn;
static mutex _lock;
bh(const bh&) = delete;
bh& operator=(const bh&) = delete;
bh(){}
public:
static bh* GetInstance() {
if (_sn == nullptr) {
_lock.lock();
if (_sn == nullptr) {
_sn = new bh();
}
_lock.unlock();
}
return _sn;
}
static void DelInstance() {
if (_sn != nullptr) {
delete _sn;
_sn = nullptr;
}
}
};