为什么在运行时不会发生双重释放或损坏错误以进行升压ptr_container

Why does double free or corruption error not happen at run time for boost ptr_container?

本文关键字:错误 container ptr 损坏 运行时 释放 为什么      更新时间:2023-10-16

我正在测试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_mapptr_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);
        }
    }
}