假设我有两个容器,它们持有指向对象的指针,这些指针共享一些元素.
从
http://www.cplusplus.com/reference/stl/list/erase/
它说:
This effectively reduces the list size
by the number of elements removed,
calling each element’s destructor
before.
如何在不调用析构函数两次的情况下从两个容器中删除对象:
例
#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);
}
请指教
解决方法:
如果你的容器持有指针,那么这些对象的析构函数将不会被调用(STL将不会遵循这些指针并调用指针的析构函数).
相反,如果您的容器本身持有全尺寸对象,则会调用这些对象的析构函数.
您在map声明和insert语句中也有一些语法错误.尝试运行以下代码.请注意,析构函数只被调用一次(对于delete语句).从不为析构语句调用析构函数.
#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!
}