c++ - ptr_vector 未正确释放

标签 c++ boost ptr-vector boost-ptr-container

我正在尝试使用 ptr_vector 来存储一些指针,但是我的 main 方法一启动就出现错误。 这是我的代码:

int main(void)
{
    boost::ptr_vector<string> temp;
    string s1 = "hi";
    string s2 = "hello";
    temp.push_back(&s1);
    temp.push_back(&s2);
    return 0;
}

这是我收到的错误消息:

Critical error detected c0000374
Windows has triggered a breakpoint in Path_Tree.exe.

This may be due to a corruption of the heap, which indicates a bug in Path_Tree.exe or     any of the DLLs it has loaded.

This may also be due to the user pressing F12 while Path_Tree.exe has focus.

The output window may have more diagnostic information.
The program '[7344] Path_Tree.exe: Native' has exited with code 0 (0x0).

我做错了什么? 谢谢!

最佳答案

ptr_vector 获取您提供给它的指针指向的对象的所有权(这意味着它在完成这些指针后调用 delete)。如果您只需要一个指针 vector ,请使用:

int main()
{
    std::vector<string*> temp;
    //s1 and s2 manage their own lifetimes
    //(and will be destructed at the end of the scope)
    string s1 = "hi";
    string s2 = "hello";
    //temp[0] and temp[1] point to s1 and s2 respectively
    temp.push_back(&s1);
    temp.push_back(&s2);
    return 0;
}

否则,您应该使用 new 分配您的字符串,然后 push_back 结果指针:

int main()
{
    boost::ptr_vector<string> temp;
    temp.push_back(new string("hi"));
    temp.push_back(new string("hello"));
    return 0;
}

如果您只需要一个字符串容器,通常的做法是字符串 vector :

int main()
{
    std::vector<string> temp;
    //s1 and s2 manage their own lifetimes
    //(and will be destructed at the end of the scope)
    string s1 = "hi";
    string s2 = "hello";
    //temp[0] and temp[1] refer to copies of s1 and s2.
    //The vector manages the lifetimes of these copies,
    //and will destroy them when it goes out of scope.
    temp.push_back(s1);
    temp.push_back(s2);
    return 0;
}

ptr_vector 旨在使具有值语义的多态对象变得更容易。如果您的字符串一开始就不是多态的,那么 ptr_vector 就完全没有必要了。

关于c++ - ptr_vector 未正确释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11972133/

相关文章:

c++ - (如何)我可以为 Boost MultiIndex 近似 "dynamic"索引( key 提取器)吗?

c++ - 如何从 boost ptr_vector 中检索引用?

c++ - boost ptr_vector 迭代器

c++ - 随机分配给 boost::ptr_vector

c++ - Qt - 从函数中获取响应

c++ - 将带有 auto 参数的 lambda 传递给另一个函数是否合法

c++ - Boost序列化编译问题

c++ - Cmake找不到boost库

c++ - 在为 Windows 和 Linux 编写的程序中是否有必要处理长数据类型?

c++ - 在 C++ 中修改后修复文件权限?