C++ 默认析构函数V.S.简单定义的析构函数
我写这篇文章是为了分析类的析构函数的行为及其对内存释放的影响,但结果似乎有点让我吃惊:C++ 默认析构函数V.S.简单定义的析构函数,c++,destructor,dynamic-memory-allocation,C++,Destructor,Dynamic Memory Allocation,我写这篇文章是为了分析类的析构函数的行为及其对内存释放的影响,但结果似乎有点让我吃惊: class test { public: test() {} ~test() {} //<-----Run the program once with and once without this line. }; int main() { test x; test *a(&x); cout << "a before memory alloca
class test {
public:
test() {}
~test() {} //<-----Run the program once with and once without this line.
};
int main()
{
test x;
test *a(&x);
cout << "a before memory allocation: " << a << endl;
a = new test;
cout << "a after memory allocation and before delete: " << a << endl;
delete a;
cout << "a after delete: " << a << endl;
return 0;
}
类测试{
公众:
test(){}
~test(){}/如果a
是指向对象的(非空)指针,则操作delete a
会触发a
指向的对象的析构函数(默认析构函数或特定析构函数)最后释放分配给该对象的内存。a
指向的内存不再是有效的对象,并且a
不能再被取消引用。但是,delete a
没有将指针a
的值设置回特定值。实际上,我很惊讶delete a
在您的情况下更改了a
的值;我无法重现这种行为。指针保持不变的事实与存储被释放的事实并不矛盾。这是可以重复使用的内存,使用您刚刚删除的指针访问此内存是您自己的错。@Gerriet您愿意吗举个例子?谢谢。我无法用默认析构函数重现指针修改:您使用的是哪种编译器?问题中描述的任何行为都与析构函数的定义方式无关。某些编译器(如Visual Studio for debug mode)会在删除后将指针设置为无效值,以帮助识别无效地址的取消引用。