gpt4 book ai didi

c++ - 检测到堆损坏 - 带指针的类

转载 作者:行者123 更新时间:2023-11-30 00:48:59 24 4
gpt4 key购买 nike

以下代码会导致断言错误。此外,警告错误消息指示检测到堆损坏。

class A {
int* a; // dynamic array of ints
A() {};
A(int size) {
a = new int[size];
}
~A() {
delete [] a;
a = nullptr;
}
}

*** in code somewhere ***
int size = 5;
A temp = A(size);

最佳答案

错误原因是:
A temp = A(size);
此行调用:

  1. A 的复制构造函数,这里:A temp = A(size); 问题是,这会创建一个浅拷贝,因为它使用默认的拷贝构造函数,而我们在类中有一个指针,需要深拷贝!
  2. A 的参数化构造函数,此处:A(size)
  3. A 的析构函数,它将删除我们由 A temp 创建的指针并将其置空。

然后当 temp 变量超出范围时,它的 Destructor 将被再次 调用,从而导致断言失败。

Solutions:

1. A temp(size);
instead of A temp = A(size);

this will only call the parametrized constructor.
or
2. Overwrite the default copy constructor to create a deep copy!

Another correction by Marco Costa
It is better to initialize a to nullptr in the default constructor.

Another correction by user4581301
Destructor should check, if a is a nullptr, before deleting.

Additional readings:
1. Why aren't pointers initialized with NULL by default?
2. Rule-of-Three becomes Rule-of-Five with C++11? suggested by Chad
3. scalar deleting destructor issue suggested by Chad

关于c++ - 检测到堆损坏 - 带指针的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30175409/

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