假设我有两个容器,它们持有指向对象的指针,并且共享一些元素。从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
只是从 map 中删除指针。如果 map 中包含的是对象而不是指针,则会调用它们的析构函数。 - Mike Seymour