2012-08-15 94 views
1

我想用ptr_vector来存储一些指针,但是一旦我的主要方法出现错误。 这里是我的代码:ptr_vector没有正确释放

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). 

我在做什么错? 谢谢!

回答

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

+0

感谢您的详细解释! – Qman 2012-08-15 15:32:48

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

可能是它自动清理,这可以解释它为什么会崩溃。 – Paranaix 2012-08-15 15:21:02

+0

@Paranaix当然,这是错误的原因。 – juanchopanza 2012-08-15 15:23:38

+0

不要写这个代码(在一般情况下,代码并不完全包含在main中)。如果'new std :: string(“hello”)抛出,'new std :: string(“hi”)'创建的字符串不会被删除,如果'temp.push_back(s1)'抛出,字符串由'new std :: string(“hello”)创建''不会被删除。 – Mankarse 2012-08-15 15:29:50

0

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

要么使用std :: vector,要么推回一个用new关键字分配的字符串。