1、将类的构造函数属性置为private,同时提供static成员函数create,在函数中new一个新对象,这样实现的类可以只可以在堆上分配。
class Base {
- protected:
- static Base* single;
- Base(){}
- public:
- ~Base(){}
- static Base* create()
- {
- single = new Base();
- return single;
- }
- void destroy()
- {
- delete this;
- }
- };
- Base* b = Base::create();
2、重载类的new操作符,使重载后的new操作符的功能为空。这样就使外层程序无法在堆上分配对象,只可以在栈上分配。