ptr_vector未正确释放

时间:2012-08-15 15:18:07

标签: 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).

我做错了什么? 谢谢!

3 个答案:

答案 0 :(得分:10)

ptr_vector取得你给它的指针所指向的对象的所有权(这意味着当它们完成时,它会对这些指针调用delete)。如果您只想要一个指针向量,请使用:

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;
}

如果你只想要一个字符串容器,通常会有一个字符串向量:

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完全没必要。

答案 1 :(得分:1)

ptr_vector旨在存储指向动态分配对象的指针。然后它获取它们的所有权并在其生命周期结束时删除它们。如果将指针传递给无法删除的对象,则会得到未定义的行为。

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

答案 2 :(得分:0)

如果你不打算将指针推回去,就没有必要使用ptr_vector。

使用std :: vector或推回使用new关键字分配的字符串。