scoped_ptr和shared_ptr可以混合使用吗?
想象一下,我在方法/函数的堆上创建了 Foo 的实例,并将其传递给调用者。我会使用什么样的智能指针?
smartptr new_foo() {
smartptr foo = new Foo();
return foo;
}
void bar() {
smartptr foo = new_foo();
foo->do_something();
// now autodelete foo, don't need it anymore
}
好吧...现在:据我了解 boost 中的那些智能指针,scoped_ptr 应该是在 bar() 中使用的指针。但我无法在 foo() 中创建它,因为它不可复制。所以我必须在 foo() 中创建一个shared_ptr并返回它。但是我现在是否必须在 bar() 中使用共享指针,或者我可以将其“转换”为 bar() 中的共享指针吗?
编辑
感谢您迄今为止的回答!所以现在我有两个解决方案:
- 仅使用
boost::shared_ptr
- 在生成器 foo() 和
boost::shared_ptr
中使用std::auto_ptr
in bar()
真诚地,我更喜欢仅升压的解决方案,并且不会将其与 STL 混合,除非确实有充分的理由这样做。那么,下一个问题:混合解决方案相对于仅升压解决方案是否有优势?
Imagine I create an instance of Foo on the heap in a method/function and pass it to the caller. What kind of smartpointer would I use?
smartptr new_foo() {
smartptr foo = new Foo();
return foo;
}
void bar() {
smartptr foo = new_foo();
foo->do_something();
// now autodelete foo, don't need it anymore
}
Ok... now: As far as I understand those smartpointers from boost, scoped_ptr should be the one to be used in bar(). But I can't create it in foo(), as it's not copyable. So I have to create a shared_ptr in foo() and return it. But do I now have to use a shared_ptr in bar(), or can I just "cast" it to an shared_ptr in bar()?
Edit
Thanks for your answers so far! So now I got two solutions:
- Use only
boost::shared_ptr
- Use
std::auto_ptr
in the generator foo() andboost::shared_ptr
in bar()
Sincerely, I prefer a boost-only solution and won't mix it with STL except there is really a good reason for doing so. So, next question: has the mixed solution any advantage over the boost only solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
boost 文档建议它们不要混合
如果您要转移所有权,那么目前另一个选项是 auto_ptr 例如,
但这将限制您如何使用 new_foo() ,即您不能使用它来填充容器(无需管理以其他方式获取资源)。 :(
对于 C++0x 和右值引用,这将是 unique_ptr 的工作,它将取代 auto_ptr 并执行您想要的操作
boost docs suggest they don't mix
If you are transfering ownership then another option at the moment would be auto_ptr e.g.
however this will then restrict how you can use new_foo() i.e. you can't use it to fill a container (without managing the resource some other way). :(
With C++0x and rvalue references this will be a job for unique_ptr, which will replace auto_ptr and just do what you want
使用boost::shared_ptr
Use
boost::shared_ptr