【发布时间】:2021-12-10 07:55:07
【问题描述】:
当我使用包含已分配内存的 B 类向量时,发生双重释放错误。
class B
{
public:
std::string a;
std::string b;
int *hehe;
B()
{
a = "Hello";
b = ", World!";
hehe = new int[7];
for (int i = 0; i < 7; ++i) {
hehe[i] = i;
}
}
~B() {
if (hehe)
delete[] hehe;
}
};
std::vector<class B> a(5);
a.erase(a.begin() + 2);
错误信息:
a.out(46830,0x10e0015c0) malloc: *** 对象 0x7ff12dc02a80 错误:未分配指针被释放 a.out(46830,0x10e0015c0) malloc: *** 在 malloc_error_break 中设置断点进行调试
这段代码运行良好。我惊呆了。
std::vector<class B> a(1);
a.erase(a.begin());
【问题讨论】:
-
我惊呆了 -- 违反了rule of 3。转到重复链接,然后转到标记为 管理资源 的部分,那里的示例看起来很熟悉吗?
-
在现代 C++ 中,几乎没有必要使用
new或new[](过去 10 年我都没有直接使用过)。使用为您管理资源的容器和智能指针。
标签: c++ vector dynamic-memory-allocation free copy-constructor