只能在堆内存上实例化的类:将析构函数定义为private,在栈上不能自动调用析构函数,只能手动调用。也可以将构造函数定义为private,但这样需要手动写一个函数实现对象的构造。

只能在栈内存上实例化的类:将函数operator new和operator delete定义为private,这样使用new操作符创建对象时候,无法调用operator new,delete销毁对象也无法调用operator delete。

#include<iostream>usingnamespacestd;//只能在堆内存上实例化的类classCHeapOnly{public:CHeapOnly(){cout<<"ConstructorofCHeapOnly!"<<endl;}voidDestroy()const{deletethis;}private:~CHeapOnly(){cout<<"DestructorofCHeapOnly!"<<endl;}};//只能在栈内存上实例化的类,就是不能使用new来构造类,把operatornew私有化classCStackOnly{public:CStackOnly(){cout<<"ConstructorofCStackOnly!"<<endl;}~CStackOnly(){cout<<"DestrucotrofCStackOnly!"<<endl;}private:void*operatornew(size_tsize){}voidoperatordelete(void*ptr){}};intmain(){CHeapOnly*pHeap=newCHeapOnly;pHeap->Destroy();CStackOnlyobjStack;return0;}//只能在堆内存上实例化的类//下面一个类也只能在堆内存上生成,将构造函数和析构函数都定义为private,//但是可以通过类的static函数创建对象,不过这个对象是不能被继承的。classFinalClass{public:staticFinalClass*GetInstance(){cout<<"Constructoroftheclass"<<endl;returnnewFinalClass;}staticvoidDeleteInstance(FinalClass*pInstance){cout<<"Destructoroftheclass"<<endl;deletepInstance;pInstance=0;}private:FinalClass(){}~FinalClass(){}};intmain(){FinalClass*fc=FinalClass::GetInstance();FinalClass::DeleteInstance(fc);return0;}