angelag angelag - 2 months ago 16
C++ Question

Take ownership of parameter by rvalue-reference

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
?

Answer

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.

Comments