mardi 27 septembre 2016

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?

Aucun commentaire:

Enregistrer un commentaire