boost::shared_ptr 标准容器

发布于 2024-07-05 20:49:40 字数 469 浏览 3 评论 0原文

假设我有一个类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掩耳倾听 2024-07-12 20:49:41

这取决于您的...部分中发生的情况

您的容器类包含 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 of p 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.

爱的十字路口 2024-07-12 20:49:41

由于 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.

余生共白头 2024-07-12 20:49:40

首先,你的问题标题说 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文