- #include<iostream>
- using namespace std;
- //只能在堆上分配内存
- class HeapOnly
- {
- public:
- HeapOnly()
- {
- cout<<"Construct."<<endl;
- }
- //pseudo dtor,注意为const,因为const也可能需要被销毁
- void destory() const
- {
- delete this;
- }
- //声明为private也是可以的,但阻碍了继承,并且即便声明为protected还是不能把它包含于对象,而使能用一个它的指针替代它
- protected:
- ~HeapOnly() //客户定义HeapOnly h;时由于稍后要调用dctor,不合法
- {
- }
- };
- //只能在栈上分配空间
- class StackOnly
- {
- public:
- StackOnly()
- {
- }
- ~StackOnly()
- {
- }
- private:
- //将new操作符私有化,在外面无法调用,因为new表达式总是调用operator new,声明为static,只为类服务,不为具体对象服务
- //注意还得把将delete与new置于同一访问层次,并且针对数组的new delete也最好一并定义为private
- static void* operator new(size_t size);
- static void operator delete(void *ptr);
- static void* operator new[] (size_t size);
- static void operator delete[] (void *ptr);
- };
- int main()
- {
- HeapOnly *hO=new HeapOnly();
- hO->destory();
- //HeapOnly he; //编译错误:HeapOnly::~HeapOnly”: 无法访问 private 成员(在“HeapOnly”类中声明),所以不能通过栈来分配这个对象的空间
- StackOnly so;
- //StackOnly *st=new StackOnly(); //StackOnly::operator new”: 无法访问 private 成员(在“StackOnly”类中声明)
- }