std::unique_ptr 作为参数的正确复制语义

发布于 2024-12-19 03:06:26 字数 730 浏览 2 评论 0原文

是否有对接口的修改可以使第二次调用正常工作?

或者我应该保持原样?

我怀疑第一个案例中的额外结构是故意设计的,因此很明显所有权正在转移。

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人生百味 2024-12-26 03:06:26

您可以将 unique_ptr 构造为临时对象:

foo4( UPBar( new Bar ));

您还可以编写 make_unique 函数模板,类似于 shared_ptr 中存在的 make_shared

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<T>(args)...));
}

foo4( make_unique<Bar>() );
// other constructors are also callable:
foo4( make_unique<Bar>(x, y, z) );

You can construct the unique_ptr as a temporary:

foo4( UPBar( new Bar ));

You can also write a make_unique function template, similar to the make_shared that exists for shared_ptr:

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<T>(args)...));
}

foo4( make_unique<Bar>() );
// other constructors are also callable:
foo4( make_unique<Bar>(x, y, z) );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文