【发布时间】:2013-10-21 21:30:06
【问题描述】:
我创建了一个示例类(仅用于学习目的),它不必使用构造函数初始化列表,因为我想使用new/delete 和malloc/free 获得相同的效果。除了不使用构造函数初始化列表之外,还有哪些其他约束?您是否认为以下代码以正确的方式模拟了新建/删除行为?
#include <iostream>
using namespace std;
class X
{
private:
int* a;
public:
X(int x)
{
this->a = new int;
*(this->a) = x;
}
~X() { delete this->a; }
int getA() { return *(this->a); }
};
class Y
{
private:
int* a;
public:
void CTor(int x)
{
this->a = new int;
*(this->a) = x;
}
void DTor() { delete this->a; }
int getA(){ return *(this->a); }
};
void main()
{
X *xP = new X(44);
cout<<xP->getA()<<endl;
delete xP;
Y *yP = static_cast<Y*>(malloc(sizeof(Y)));
yP->CTor(44);
cout<<yP->getA()<<endl;
yP->DTor();
free(yP);
system("pause");
}
不使用delete xP,程序结束时会自动调用析构函数,但不会释放空闲存储区(即xP的空闲存储区,a字段的空闲存储区将被释放)。使用delete xP 时,会调用析构函数,然后完全释放空闲存储。
如果我错了,请纠正我。
【问题讨论】:
-
如果你不调用
delete,除非你手动调用,否则析构函数不会被调用。 -
...如果您不调用
new,则不会调用构造函数。 -
...没什么好说的...
-
@Irbis:或者对于另一个对象中的对象,它们是直接成员(不是通过 new 创建的)。就像我在回答中使用
std::string的例子一样。 -
析构函数也可以在使用smart pointer时自动调用。
标签: c++