安全的 std::tr1::shared_ptr 用法
这种方法不安全吗?
#include <tr1/memory>
Foo * createFoo()
{
return new Foo(5);
}
int main()
{
std::tr1::shared_ptr<Foo> bar(create());
return 0;
}
或者 createFoo
返回一个 shared_ptr
对象会更好吗?
Is this approach unsafe?
#include <tr1/memory>
Foo * createFoo()
{
return new Foo(5);
}
int main()
{
std::tr1::shared_ptr<Foo> bar(create());
return 0;
}
Or would it be preferable for createFoo
to return a shared_ptr<Foo>
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的示例按照您编写的方式是安全的。但是,您可以通过让工厂方法
createFoo()
返回自动指针而不是原始指针来使其更加防泄漏。这样你就可以保证不会有泄漏。所以你会得到的是:
当然也可以让你的工厂方法返回一个shared_ptr,但这可能被视为矫枉过正,因为返回的指针通常会很快超出范围,因为它将被用于赋值或构造函数。此外,使用 auto_ptr 可以更清楚地说明指针的预期用途,当不熟悉代码的人必须理解它时,这总是一个优点。
Your example is safe the way you've written it. However, you could make it even more leak-proof by having your factory method
createFoo()
return an auto pointer instead of a raw pointer. That way you are guaranteed that there will be no leaks.So what you'd get is:
It is of course also possible to have your factory method return a shared_ptr, but this might be seen as overkill, since the returned pointer will generally go out of scope quite quickly, since it will be used in an assignment or constructor. Furthermore, using auto_ptr states the intended use of the pointer more clearly, which is always a plus when people unfamiliar with your code have to understand it.
这个例子是安全的:如果
shared_ptr
构造函数抛出异常,它会在抛出异常之前删除
其指针参数(标准草案,20.9.11.2.1)。create
是否应返回shared_ptr
取决于其客户端可能合理地希望对其结果执行的操作。如果他们所做的只是将其包装在shared_ptr
中,则将其返回以获得额外的安全性。 (是的,shared_ptr
可能会引入一些耦合。)The example is safe: if the
shared_ptr
constructor throws an exception, itdelete
's its pointer argument before throwing (draft standard, 20.9.11.2.1).Whether
create
should return ashared_ptr
depends on what its clients may reasonably want to do with its result. If all they ever do is wrap it in ashared_ptr
, then return that for extra safety. (Yes,shared_ptr
may introduce some coupling.)