2010-08-19 35 views
3

假設我有兩個容器,它們持有指向對象的指針,它們共享其中的一些元素。 從 http://www.cplusplus.com/reference/stl/list/erase/ 它說:STL容器,從兩個容器中移除對象

這有效地通過前調用每個元素的析構函數 刪除元素的數量, 降低了列表的大小 。

我怎樣才能把兩個容器中的對象,而不調用析構函數兩次:

例如

#include <map> 
#include <string> 
using namespace std; 
//to lazy to write a class 
struct myObj{ 
      string pkid; 
      string data; 
}; 
map<string,*myObj> container1; 
map<string,*myObj> container2; 

int main() 
{ 
     myObj * object = new myObj(); 
     object->pkid="12345"; 
     object->data="someData"; 
     container1.insert(object->pkid,object); 
     container2.insert(object->pkid,object); 

     //removing object from container1 
     container1.erase(object->pkid); 
     //object descructor been called and container2 now hold invalid pointer 

     //this will call try to deallocate an deallocated memory 
     container2.erase(object->pkid); 

} 

請指教

+4

事實上,對象析構函數根本沒有被調用; 'erase'只是從地圖上移除指針。如果地圖包含對象而不是指針,那麼它會調用它們的析構函數。 – 2010-08-19 18:36:51

回答

4

如果容器持有指針,那麼這些對象的析構函數不會被調用(STL的將不遵循這些指針和調用指針對象的析構函數)。相反,如果你的容器本身持有全尺寸的對象,那麼將調用這些對象的析構函數。

您的地圖聲明和插入語句中也有一些語法錯誤。嘗試運行以下代碼。請注意,析構函數只被稱爲一次(用於刪除語句)。 析構函數永遠不會被調用擦除語句

#include <map> 
#include <string> 
#include <iostream> 
using namespace std; 
//to lazy to write a class 
struct myObj{ 
    ~myObj() { 
     cout << "DESTRUCTION" << endl; 
    } 
      string pkid; 
      string data; 
}; 
map<string,myObj*> container1; 
map<string,myObj*> container2; 

int main() 
{ 
     myObj * object = new myObj(); 
     object->pkid="12345"; 
     object->data="someData"; 
     container1.insert(pair<string,myObj*>(object->pkid,object)); 
     container2.insert(pair<string,myObj*>(object->pkid,object)); 

     //removing POINTER from container1 
     container1.erase(object->pkid); 
     //object's destructor has NOT been called yet 

     //removing POINTER from container2 
     container2.erase(object->pkid); 
     //object's destructor STILL hasn't been called 

     delete object; // DESTRUCTION! 
} 
+1

我明白了。所以在指針的情況下,我需要在將它們從所有容器中拉出之後將其明確刪除。 謝謝! – Alex 2010-08-19 19:18:45