// 特殊类设计
// 1. 设计一个类 只能在堆上创建
// (1) 将累的构造函数私有,拷贝构造声明成私有,防止别人调用拷贝在栈上生成对象。
// (2) 提供一个静态成员函数,在该静态成员函数中完成堆对象的创建。
class HeapOnly {
public:
static HeapOnly* CreateObject() {
return new HeapOnly;
}
private:
HeapOnly() {}
// C++ 98 只声明不实现;
HeapOnly(const HeapOnly&);
// or
//C++11
HeapOnly& operator=(const HeapOnly&) = delete;
};
// 2.设计一个类只能在栈上创建;
// 方案1:将构造函数私有化,让后设计一个静态方法返回创建对象即可!
class StackOnly1 {
public:
static StackOnly1 CreateObject() {
return StackOnly1();
}
private:
void* operator new(size_t size);
void operator delete(void* p);
};
// 方案2 : 屏蔽new 因为new 在底层调用void * operator new(size_t size) 函数只需要将该函数屏蔽掉即可!也要防止定位new
class StackOnly2 {
public:
StackOnly2 CreateObject() {};
private:
void* operator new(size_t size);
void operator delete(void* p);
};
// 3. 设计一个类不能被拷贝!
// 拷贝只会发生在两个场景中: 拷贝构造函数以及赋值运算符重载,因此想要让一个类禁止拷贝只需要让该类不能调用拷贝构造函数
// 以及赋值运算符重载即可!
class UnCopyBean {
UnCopyBean(const UnCopyBean&) = delete;
UnCopyBean& operator=(const UnCopyBean&) = delete;
};
// 4. 设计一个类不能被继承
// C++ 98
class NoInHerit {
static NoInHerit GetInstance() {
return NoInHerit();
}
private:
NoInHerit(){}
};
// C++ 11
class NoInHerit1 final {
//....
};
// 4. 单例模式
// 饿汉模式
class Sington {
public:
static Sington* GetInstance() {
return &m_instance;
}
private:
Sington() {};
Sington(Sington const&) = delete;
Sington& operator=(Sington const&) = delete;
static Sington m_instance;
};
Sington Sington::m_instance;
// 懒汉模式
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class Sigton {
public:
static Sigton* GetInstance() {
if (nullptr == m_instance) {
m_mtx.lock();
if (nullptr == m_instance) {
m_instance = new Sigton();
}
m_mtx.unlock();
}
return m_instance;
}
// 实现一个内嵌垃圾回收类
class CGarbo {
public:
~CGarbo() {
if (Sigton::m_instance) {
delete Sigton::m_instance;
}
}
};
static CGarbo Garbo;
private:
Sigton() {}; // 构造私有!
// 防拷贝!
Sigton(Sigton const&) = delete;
Sigton& operator=(Sigton const&) = delete;
static Sigton* m_instance; // 单例指针对象.
static mutex m_mtx; // 互斥量.
};
Sigton* Sigton::m_instance = nullptr;
Sigton::CGarbo Garbo;
mutex Sigton::m_mtx;
自学C++ day14 特殊类
最新推荐文章于 2024-07-25 10:17:46 发布