删除指针矢量时避免双重免费
我尝试了以下内容,但是在运行时获得了分割故障和“在TCACHE2中的双免费检测到”:
class A {
...
};
class B {
public:
B(...) {...}
~B() {
for(int i=0;i<As.size();i++) {
if(As[i] != nullptr) {
delete As[i];
As[i] = nullptr;
}
}
}
std::vector<A*> As;
};
int main()
{
A* a1 = new A(...);
A* a2 = new A(...);
B* b1 = new B(...);
b* b2 = new B(...);
b1.As.push_back(a1);
b1.As.push_back(a2);
b2.As.push_back(a1);
delete b1;
delete b2;
return 0;
}
有什么办法可以保证我只删除这些指针一次?
I have tried the following, but getting segmentation fault and "double free detected in tcache2" during runtime:
class A {
...
};
class B {
public:
B(...) {...}
~B() {
for(int i=0;i<As.size();i++) {
if(As[i] != nullptr) {
delete As[i];
As[i] = nullptr;
}
}
}
std::vector<A*> As;
};
int main()
{
A* a1 = new A(...);
A* a2 = new A(...);
B* b1 = new B(...);
b* b2 = new B(...);
b1.As.push_back(a1);
b1.As.push_back(a2);
b2.As.push_back(a1);
delete b1;
delete b2;
return 0;
}
Is there any way I could assure that I delete these pointers only once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,您正在将相同的指针存储在两个阵列中。是的,您正在删除两次。这就是为什么在现代C ++中劝阻原始指针的原因。改用智能指针。
之后,您可以像其他任何指针一样使用它们,除了类型不同,您不必删除它们。他们参考计数。如果需要,只需将值设置为nullptr即可。
Okay, you're storing the same pointer in two arrays. So yes, you're deleting it twice. This is why the use of raw pointers has become discouraged in modern C++. Use smart pointers instead.
After that, you can use them just like any other pointer, except the type is different and you do NOT have to delete them. They reference count. Just set the value to nullptr if you want.