假设我有两个容器,保存指向对象的指针,它们共享它们的一些元素。 从 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 声明和插入语句中也有一些语法错误。尝试运行以下代码。请注意,析构函数仅被调用一次(对于删除语句)。 永远不会为删除语句调用析构函数。
#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!
}
关于c++ - STL 容器,从两个容器中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3524915/