13

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?

lt.ungustl
  • 211
  • 1
  • 8

2 Answers2

4

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.

Chris Drew
  • 14,926
  • 3
  • 34
  • 54
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));
for_stack
  • 21,012
  • 4
  • 35
  • 48
  • 3
    Of course this is also an option. However, it doesn't enforce to move the object and therefore unnecessary copies could be made. – lt.ungustl Sep 27 '16 at 10:10
  • 2
    @angelag In this case, I think pass-by-value might be a better option. If you want `Data` always has only ONE owner, then you should make it non-copyable, and pass `Data` by value works as what you did with `unique_ptr`. Otherwise, i.e. `Data` is copyable, pass-by-value gives the client two choices: copy it or 'move' it. It's more flexible, and sometimes the client might want to keep a copy of `Data` after passing it to `A`'s constructor. – for_stack Sep 27 '16 at 12:25