STL容器,从两个容器中删除对象
假设我有两个容器,保存指向对象的指针,它们共享一些元素。 从 http://www.cplusplus.com/reference/stl/list/erase/< /a> 它说:
这有效地减少了列表大小 根据删除的元素数量, 调用每个元素的析构函数 之前。
如何从两个容器中删除对象而不调用析构函数两次:
示例
#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);
}
请建议
Suppose I have two containers , holding pointers to objects ,which share some of their elements .
from
http://www.cplusplus.com/reference/stl/list/erase/
it says that :
This effectively reduces the list size
by the number of elements removed,
calling each element's destructor
before.
How can I remove an object from both containers without calling the destructor twice:
example
#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);
}
please advice
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的容器持有指针,则不会调用这些对象的析构函数(STL 不会遵循这些指针并调用被指向对象的析构函数)。
相反,如果您的容器本身保存全尺寸对象,那么将调用这些对象的析构函数。
您的映射声明和插入语句中也存在一些语法错误。尝试运行以下代码。请注意,析构函数仅被调用一次(对于删除语句)。 擦除语句永远不会调用析构函数。
If your containers are holding pointers, then the destructor for those objects won't be called (the STL won't follow those pointers and call the pointee's destructor).
Conversely, if your containers were holding the full-size objects themselves, then the destructor for those objects would be called.
You also had some syntax errors in your map declaration and insert statements. Try running the following code. Notice that the destructor is only called once (for the delete statement). The destructor is never called for the erase statements.
使用引用计数器来确定是否所有容器都已删除您的对象。 Boost 有一个引用计数器类
shared_ptr
。http://www.boost.org/doc/libs/ 1_44_0/libs/smart_ptr/shared_ptr.htm
Use reference counters to determine if all of your containers have deleted your object. Boost has a reference counter class
shared_ptr
.http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/shared_ptr.htm