gpt4 book ai didi

c++ - 为什么使用赋值时不调用堆栈变量的析构函数?

转载 作者:行者123 更新时间:2023-12-01 18:59:26 28 4
gpt4 key购买 nike

这段愚蠢的代码已经花了我两个小时,我不明白为什么第一个元素的析构函数,即大小为 7 的元素,没有被调用?为 new uint16_t[7] 分配的内存会发生什么情况?

#include <iostream>

using namespace std;

struct Node
{
Node(uint16_t n) : p(new uint16_t[n]) {
cout<<"Constructed with size= "<<n<<", memory addr: "<<(p)<<endl;
for(uint16_t i=0; i<n; i++) p[i] = n;
}

~Node() {
cout<<"Destructor for p[0] = "<< *p <<" with memory addr: "<<p<<endl;
delete[] p;
}

uint16_t *p;
};

int main()
{
{
Node nd1(7);
{
nd1 = Node(3);
cout << "1st place holder" << endl;
}
cout << "2nd place holder" << endl;
}

return 0;
}

输出为

Constructed with size= 7, memory addr: 0x158cc20                                                                                                                                   
Constructed with size= 3, memory addr: 0x158cc40
Destructor for p[0] = 3 with memory addr: 0x158cc40
1st place holder
2nd place holder
Destructor for p[0] = 0 with memory addr: 0x158cc40
*** Error in `./a.out': double free or corruption (fasttop): 0x000000000158cc40 ***
Aborted (core dumped)

最佳答案

I cannot figure out why the destructor of the first element, the one with size 7, not called?

称为。事实上,正是该析构函数导致了程序崩溃。程序的行为是未定义的,因为析构函数删除了先前由临时对象的析构函数删除的相同指针值。在此之前,它通过该无效指针进行间接访问。

<小时/>

What happens to the memory allocated for new uint16_t[7]?

当您对对象进行分配时,指向内存的指针丢失了。这称为内存泄漏。

关于c++ - 为什么使用赋值时不调用堆栈变量的析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59887006/

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