2012-08-15 96 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關鍵字分配的字符串。