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);
};
int main()
{
StackOnly s; //okay
StackOnly *p = new StackOnly; //wrong
return 0;
}

本文探讨了C++中堆内存和栈内存对象的管理方式。通过两个示例类,HeapOnly和StackOnly,演示了如何创建及销毁不同类型的内存对象,并展示了它们在程序中的生命周期区别。
6万+

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



