Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 默认析构函数V.S.简单定义的析构函数_C++_Destructor_Dynamic Memory Allocation - Fatal编程技术网

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)会在删除后将指针设置为无效值,以帮助识别无效地址的取消引用。