std::unique_ptr 作为参数的正确复制语义
是否有对接口的修改可以使第二次调用正常工作?
或者我应该保持原样?
我怀疑第一个案例中的额外结构是故意设计的,因此很明显所有权正在转移。
#include <memory>
struct Bar { };
typedef std::unique_ptr<Bar> UPBar;
void foo1( UPBar p ) { }
void foo2( UPBar p ) { foo1( move( p )); }
void foo3( UPBar p ) { foo2( move( p )); }
void foo4( UPBar p ) { foo3( move( p )); }
int main(int argc, char** argv)
{
UPBar p( new Bar );
foo4( move( p )); // ok, but requires an extra construction vs line below
foo4( new Bar ); // fails: any modification to get this to work?
return 0;
}
第二个问题:如果我更改传递给 RValue-References (&&) 的所有参数,这样做有什么缺点吗?事实上,我是否应该确保所有 std::unique_ptr<>
参数均由 RValue-References 传递?
Is there a modification to the interface that can get the second call to work?
Or should I leave things as is?
I suspect the extra construction in the first case was designed that way on purpose so it is clear that ownership is being transferred.
#include <memory>
struct Bar { };
typedef std::unique_ptr<Bar> UPBar;
void foo1( UPBar p ) { }
void foo2( UPBar p ) { foo1( move( p )); }
void foo3( UPBar p ) { foo2( move( p )); }
void foo4( UPBar p ) { foo3( move( p )); }
int main(int argc, char** argv)
{
UPBar p( new Bar );
foo4( move( p )); // ok, but requires an extra construction vs line below
foo4( new Bar ); // fails: any modification to get this to work?
return 0;
}
Second Question: If I change all the parameters passed to RValue-References (&&), is there any disadvantage in doing so? In fact, should I ensure that all my std::unique_ptr<>
parameters are passed by RValue-References?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
unique_ptr
构造为临时对象:您还可以编写
make_unique
函数模板,类似于shared_ptr 中存在的
make_shared
:You can construct the
unique_ptr
as a temporary:You can also write a
make_unique
function template, similar to themake_shared
that exists forshared_ptr
: