这个愚蠢的代码片段已经让我花费了两个小时,我无法弄清楚为什么第一个元素(大小为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)