传递 boost::shared_ptr 引用的安全性
我的问题是,以下代码片段是我的资源管理器的一部分,它的故障安全性如何:
bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel)
{
std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;
seeker = models.find(name);
if (seeker == models.end())
return false;
newModel = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
return true;
}
private:
std::map< std::string, boost::scoped_ptr<Asset::Model> > models;
因为通过引用传递boost的shared_ptr实际上不是shared_ptr概念的一部分,如果我只在这个范围内使用它,我会遇到麻烦吗?
my question is, how fail-safe is the following code snippet which is part of my resource manager:
bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel)
{
std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;
seeker = models.find(name);
if (seeker == models.end())
return false;
newModel = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
return true;
}
private:
std::map< std::string, boost::scoped_ptr<Asset::Model> > models;
because passing boost's shared_ptr by reference is actually not part of the shared_ptr concept, if i only use it in this scope, could i run into trouble?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种用法是安全的,因为无论通过引用传入的
shared_ptr<>
都会减少其引用计数(假设从返回的
不是同一对象的shared_ptr<>
seer->second->Copy()shared_ptr
),因此它指向的对象可能会被删除。具体来说,您不会从原始指针创建第二个
shared_ptr<>
(这是一个错误,因为它将创建第二个不相关的shared_ptr<>
)单独的引用计数,因此是对象的第二个所有者)。您的函数是否提供您想要的行为取决于您想要什么。
This usage is safe, in that whatever the
shared_ptr<>
passed in through the reference will have it's refcount reduced (assuming that theshared_ptr<>
returned fromseeker->second->Copy()
isn't ashared_ptr<>
to the same object) and therefore the object it will be pointing to might be deleted.Specifically, you aren't creating a second
shared_ptr<>
from a raw pointer (which is an error because it would create a second, unrelatedshared_ptr<>
with a separate refcount, and therefore a second owner of the object).Whether your function provides the behavior you want depends on what you want.
我猜你想做这样的事情:
在这种情况下你应该没问题。
但是您不需要在此处使用参考。如果没有找到元素,只需返回一个
shared_ptr
并将其设置为 0:但是我注意到您在标准容器中使用
scoped_ptr
- AFAIK 这是不可能的。I guess you want to do something like this:
In this case you should be fine.
However you don't need to use a reference here. Just return a
shared_ptr
and set it to 0 if no element was found:However I noticed you are using
scoped_ptr
in a standard container - which AFAIK is not possible.