class HeapOnly
{
public:
HeapOnly()
{
cout<<"constructor. "<<endl;
}
void destroy()
{
delete this;
}
private:
~HeapOnly(){}
};
{
public:
HeapOnly()
{
cout<<"constructor. "<<endl;
}
void destroy()
{
delete this;
}
private:
~HeapOnly(){}
};
int main()
{
HeapOnly *p = new HeapOnly;
p->destroy();
HeapOnly h;
h.Output();
{
HeapOnly *p = new HeapOnly;
p->destroy();
HeapOnly h;
h.Output();
return 0;
}
}
#include <iostream>
using namespace std;
class StackOnly
{
public:
StackOnly()
{
cout<<"constructor." <<endl;
}
~StackOnly()
{
cout<<"destructor." <<endl;
}
private:
void *operator new (size_t);
};
{
public:
StackOnly()
{
cout<<"constructor." <<endl;
}
~StackOnly()
{
cout<<"destructor." <<endl;
}
private:
void *operator new (size_t);
};
{
StackOnly s; //okay
StackOnly *p = new StackOnly; //wrong
return 0;
}
本文探讨了C++中堆和栈的使用,包括如何创建、使用和销毁堆和栈对象,通过实例展示了堆Only类和StackOnly类的生命周期管理。
4219

被折叠的 条评论
为什么被折叠?



