gpt4 book ai didi

c++ - C+ : Destructor for same instance of an object called twice

转载 作者:太空狗 更新时间:2023-10-29 23:49:46 25 4
gpt4 key购买 nike

所以基本上我在 VS2013 中有一些看起来像这样的 C++ 代码

#include "stdafx.h"
#include <malloc.h>
#include <stdio.h>

class Test_Class {
public:
Test_Class() {
printf("In Test_Class()\n");
allocated_array = (int*)malloc(sizeof(int) * 64);
printf("Allocated %p\n", allocated_array);
}

~Test_Class() {
printf("In ~Test_Class()\n");
printf("Freeing %p\n", allocated_array);
free(allocated_array);
printf("Freed %p\n", allocated_array);
}
private:
int* allocated_array;
};

class Holder {
public:
Holder() {
printf("In Holder()\n");
m_test_class = Test_Class();
}

~Holder() {
printf("In ~Holder()\n");
}
private:
Test_Class m_test_class;
};

class Game {
public:
Game() {
printf("In Game()\n");
m_holder = Holder();
}

~Game() {
printf("In ~Game()");
}
private:
Holder m_holder;
};

int main()
{
printf("In main()\n");
Game game = Game();
return 0;
}

当运行时,给我这个输出:

http://i.imgur.com/g8vCdIo.png

我想知道的是,为什么同一个 Test_Class 对象的析构函数在崩溃前被调用两次(因为试图释放同一个指针两次)。我检查了调试器,以确保它不仅仅是一个类的新实例,它被赋予了与另一个对象相同的指针,而且确实是完全相同的对象。

我知道由于 Test_Class 对象是 Holder 的成员,它会创建一个 Test_Class 对象,然后创建另一个对象并销毁旧对象(它似乎这样做),但是这种调用析构函数的奇怪行为当我在 Game 类中创建 Holder 类型的成员时,似乎也会发生同样的情况。显然我缺少一些东西。

最佳答案

原因是,您的编译器无法消除复制赋值 Game game = Game();

正确的代码应该是Game game;

您的代码所做的是将一个对象构造为右值,并将其分配给一个作为左值的新对象 game。所以在这一行 Game game = Game(); 中构造了两个对象,其中一个在赋值后立即销毁。

编辑:

同样适用于 m_Holder 等等 - 当然。

关于c++ - C+ : Destructor for same instance of an object called twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com