提高shared_ptr的:差分算子之间=和复位? [英] boost shared_ptr: difference between operator= and reset?
问题描述
是否有低于code两片有何区别?是它们中的任何preferable其他?
运算符= 搜索
的boost :: shared_ptr的<&胡说GT;富; // foo.ptr应为NULL
富=提高:: shared_ptr的<&胡说GT;(新布拉赫()); //涉及到一个shared_ptr创建和复制?
重置搜索
的boost :: shared_ptr的<&胡说GT;富; // foo.ptr应为NULL
foo.reset(新布拉赫()); // foo.ptr现在应该指向一个新的对象胡说
请注意:我需要定义的shared_ptr然后将其设置在不同的线路,因为我在一块code像使用它:
的boost :: shared_ptr的<&胡说GT;富;
尝试
{
foo.reset ...
}
富...
运算符=
分配的shared_ptr
来一的shared_ptr
,而重置
发出的shared_ptr
采取的所有权指针。所以,基本上没有您发布的例子没有什么区别。这就是说,你应该preFER他们都没有,只是用<一个href=\"http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/make_shared.html\"><$c$c>make_shared$c$c>:
富=提振:: make_shared&LT;&胡说GT;();
另外,如果可能的话,你可以prevent具有由一个单独的函数,仅仅返回一个包裹try-catch块来声明的shared_ptr
不用初始化的shared_ptr
来新创建的对象:
的boost :: shared_ptr的&LT;&胡说GT; createBlah(){
尝试{
// 做东西
返回newBlah;
}
赶...
}
Are there any differences between the two pieces of code below? Is any of them preferable to the other?
operator=
boost::shared_ptr<Blah> foo; // foo.ptr should be NULL
foo = boost::shared_ptr<Blah>(new Blah()); // Involves creation and copy of a shared_ptr?
reset
boost::shared_ptr<Blah> foo; // foo.ptr should be NULL
foo.reset(new Blah()); // foo.ptr should point now to a new Blah object
Note: I need to define the shared_ptr and then set it in a different line because I'm using it in a piece of code like:
boost::shared_ptr<Blah> foo;
try
{
foo.reset...
}
foo...
operator=
assigns a shared_ptr
to a shared_ptr
, while reset
makes a shared_ptr
take ownership of a pointer. So, basically there is no difference between the examples you have posted. That said, you should prefer neither of them and just use make_shared
:
foo = boost::make_shared<Blah>();
Also, if possible, you can prevent having to declare a shared_ptr
without initialization by wrapping the try-catch block in a separate function that simply returns a shared_ptr
to the newly created object:
boost::shared_ptr<Blah> createBlah() {
try {
// do stuff
return newBlah;
}
catch ...
}
这篇关于提高shared_ptr的:差分算子之间=和复位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!