c++使一个对象可以在栈上创建,但是不能在堆上创建。方法是通过重载new和delete操作符并且私有化,这样就可以禁止对象在堆上分配了(因为一个对象在堆上的创建只能通过new来实现)
Class A
{
Private:
Void* operator new (size_t size)
{
Return malloc(size);
}
Void operator delete(void* ptr)
{
If (ptr)
Free(ptr);
}
Public:
A(){}
}
Int main()
{
A a;//在栈上创建,正确
A* a = new A;//在堆上创建,编译错误
}