假設我有兩個容器,它們持有指向對象的指針,它們共享其中的一些元素。 從 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);
}
請指教
事實上,對象析構函數根本沒有被調用; 'erase'只是從地圖上移除指針。如果地圖包含對象而不是指針,那麼它會調用它們的析構函數。 – 2010-08-19 18:36:51