为什么在运行时不会发生双重释放或损坏错误以进行升压ptr_container
Why does double free or corruption error not happen at run time for boost ptr_container?
我正在测试boost ptr_containers并编写了一个小程序,如下所示:
class Test {
public:
~Test() {
cout << "Test Destructor called" << endl;
}
};
int main(int argc, char** argv) {
boost::ptr_map<int, Test> TestContainer;
boost::ptr_vector<Test> TestVector;
for (int i=0; i<2; ++i) {
Test* ptr = new Test();
TestContainer.insert(i, ptr);
TestVector.push_back(ptr);
}
}
一旦我执行程序,"测试析构函数调用"被打印四次,程序成功完成。我预计打印会发生 2 次,然后"无双倍......"将抛出错误消息。为什么在上述情况下没有发生,而是在原始指针(Test*)上发生?
ptr_map
和ptr_vector
拥有自己的元素。
程序不正确。一次在两个容器中插入相同的元素会导致双重删除。
已删除指针上的删除行为未定义。任何事情都可能发生。查看未定义的行为
使用像valgrind这样的工具来捕捉这个。
如果您确实想知道,修复此示例的最简单方法是对其中一个容器使用非拥有指针。请务必管理元素的相对生存期:
#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
#include <map>
class Test {
public:
~Test() {
std::cout << "Test Destructor called" << std::endl;
}
};
int main() {
boost::ptr_vector<Test> TestVector;
{
std::map<int, Test*> TestContainer;
for (int i=0; i<2; ++i) {
Test* ptr = new Test();
TestContainer.emplace(i, ptr);
TestVector.push_back(ptr);
}
}
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"