只在堆上创建对象
方法:将析构函数设置为私有或受保护的
class OnlyHeap{
public:
void destory() const{
delete this;
}
protected:
~OnlyHeap(){}
};
int main(){
//OnlyHeap oh; // Error: Variable of type 'OnlyHeap' has protected destructor
const OnlyHeap* ohp = new OnlyHeap(); // OK
ohp->destory();
}
不允许在堆上创建
方法:重载 operator new 和 operator new[],将其设置为私有或受保护的
class NoHeap{
protected:
static void* operator new(size_t); // #1: 阻止创建单个对象
static void* operator new[](size_t); // #2: 阻止创建对象数组
};
int main(){
// NoHeap* nhp = new NoHeap; // Error 'operator new' is a protected member of 'NoHeap'
// NoHeap* nhps = new NoHeap[1]; // Error: 'operator new[]' is a protected member of 'NoHeap'
NoHeap nh; // OK
}