boost::shared_ptr 标准容器
假设我有一个类 foo,并希望使用 std::map 来存储一些 boost::shared_ptrs,例如:
class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
如果我向映射添加一个新的 foo_sp 但使用的密钥已经存在,现有条目是否会被删除? 例如:
foo_sp_map m;
void func1()
{
foo_sp p(new foo);
m[0] = p;
}
void func2()
{
foo_sp p2(new foo);
m[0] = p2;
}
原来的指针(p)被p2替换后会被释放吗? 我很确定会这样,但我认为值得询问/分享。
Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:
class foo;
typedef boost::shared_ptr<foo> foo_sp;
typeded std::map<int, foo_sp> foo_sp_map;
foo_sp_map m;
If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example:
foo_sp_map m;
void func1()
{
foo_sp p(new foo);
m[0] = p;
}
void func2()
{
foo_sp p2(new foo);
m[0] = p2;
}
Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于您的...部分中发生的情况
您的容器类包含 foo_sp 实例的副本,当您执行
m[0] = p2;
的副本时最初位于该位置的 >p 超出了范围。 届时,如果没有其他 foo_sp 引用它,它将被删除。如果第二行
foo_sp p(new foo);
中声明的副本仍然存在,那么内存将不会被释放。 一旦删除了对该条目的所有引用,该条目将被删除。It depends on what happens in your ... section
Your container class contains copies of instances of foo_sp, when you execute
m[0] = p2;
the copy ofp
that was originally in that place goes out of scope. At that time it will be deleted if there are no other foo_sp refers to it.If the copy that was declared in the second line
foo_sp p(new foo);
is still around then the memory will not be deallocated. The entry will be delete once all references to it have been removed.由于 stackoverflow 不允许我发表评论,我就回答一下。 :/
我没有看到“p”超出范围,因此它指向的对象将不会被释放。 “p”仍会指向它。
Since stackoverflow won't allow me to comment, I'll just answer. :/
I don't see "p" going out of scope, so the object pointed to by it will not be freed. "p" will still point to it.
首先,你的问题标题说 boost::auto_ptr ,但你实际上的意思是 boost::shared_ptr
是的,原始指针将被释放(如果没有进一步的共享引用)。
First off, your question title says boost::auto_ptr, but you actually mean boost::shared_ptr
And yes, the original pointer will be freed (if there are no further shared references to it).