【发布时间】:2010-08-19 18:17:17
【问题描述】:
假设我有两个容器,持有指向对象的指针,它们共享它们的一些元素。 从 http://www.cplusplus.com/reference/stl/list/erase/ 它说:
这有效地减少了列表大小 通过删除的元素数量, 调用每个元素的析构函数 之前。
如何在不调用析构函数两次的情况下从两个容器中删除一个对象:
例子
#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只是从地图中删除指针。如果映射包含对象而不是指针,那么它将调用它们的析构函数。
标签: c++ stl map containers