通过右值引用获取参数的所有权 [英] Take ownership of parameter by rvalue-reference

查看:96
本文介绍了通过右值引用获取参数的所有权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚我的类 A 的构造函数将拥有传递的 Data 参数的所有权。显而易见,要做的就是按值获取 unique_ptr

I want to make clear that the constructor of my class A will take ownership of the passed Data parameter. The obvious thing to do is take a unique_ptr by value:

class A
{
public:
    A(std::unique_ptr<Data> data) : _data(std::move(data)) { }

    std::unique_ptr<Data> _data;
};

但是,在我的用例中,没有理由使用 Data 应该是一个指针,因为值类型就足够了。我想想要明确指出的唯一剩下的选择就是 Data 将由 A 拥有,是通过右值传递-引用:

However, for my use-case, there is no reason why Data should be a pointer, since a value type would suffice. The only remaining option that I could think of to make really clear that Data will be owned by A is pass by rvalue-reference:

class A
{
public:
    A(Data&& data) : _data(std::move(data)) { }

    Data _data;
};

这是表示所有权的有效方法,还是有更好的选择而不使用 unique_ptr

Is this a valid way to signal ownership or are there better options to do this without using unique_ptr?

推荐答案

是的,我认为这是一种有效的方法。

Yes, I think it is a valid way.

unique_ptr 的情况下,它是不可复制的,因此不存在有人意外复制的危险并不打算因此按值传递和按值传递引用均表示拥有所有权。

In the case of unique_ptr, it is non-copyable, so there is no danger of someone accidentally making a copy when they didn't intend to so both pass-by-value and pass-by-rvalue-reference signify taking ownership.

对于 Data ,是您拥有所有权的按值传递参考文件,并且在调用者不希望的情况下,调用者无意抄袭也没有危险。

In the case of Data, pass-by-rvalue-reference documents that you are taking ownership and there is no danger of the caller accidentally making a copy when they didn't intend to.

这篇关于通过右值引用获取参数的所有权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆