问题
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;
};
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;
};
Is this a valid way to signal ownership or are there better options to do this without using unique_ptr
?
回答1:
Yes, I think it is a valid way.
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.
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.
回答2:
Yes, it's a valid way. You can also pass it by value:
class A {
A(Data data) : _data(std::move(data)) { }
};
Data data;
A a(std::move(data));
来源:https://stackoverflow.com/questions/39721654/take-ownership-of-parameter-by-rvalue-reference