Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 815
lt.ungustl Avatar asked Sep 27 '16 09:09

lt.ungustl


People also ask

Can you pass an rvalue by reference?

Yes, pass-by-rvalue-reference got a point. The rvalue reference parameter means that you may move the argument, but does not mandate it. Yes, pass-by-value got a point.

When use rvalue reference?

In C++11, however, the rvalue reference lets us bind a mutable reference to an rvalue, but not an lvalue. In other words, rvalue references are perfect for detecting whether a value is a temporary object or not.

Can a function return an rvalue?

Typically rvalues are temporary objects that exist on the stack as the result of a function call or other operation. Returning a value from a function will turn that value into an rvalue. Once you call return on an object, the name of the object does not exist anymore (it goes out of scope), so it becomes an rvalue.

What are rvalue references?

Rvalue references is a small technical extension to the C++ language. Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions. They are primarily meant to aid in the design of higer performance and more robust libraries.


1 Answers

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.

like image 69
Chris Drew Avatar answered Sep 28 '22 18:09

Chris Drew