samedi 6 juillet 2019

How to keep object passed by rvalue reference alive without copy?

I am trying to pass Child as r-value to Parent and save it there without any copies.

Parent p{ Child{} };

cout << "----Done----" << endl;

And now the implementation:

class Child
{
public:
    Child() { cout << "Child: created" << endl; }

    ~Child() { cout << "Child: destroyed" << endl; }
};

class Parent
{
    // store as r-value ref
    Child&& child;

public:
    // pass by r-value ref and move
    Parent(Child&& c) :child(move(c))
    {
        cout << "Parent: created" << endl;
    }

    ~Parent() { cout << "Parent: destroyed" << endl; }
};

The output is:

Child: created
Parent: created
Child: destroyed
------Done------
Parent: destroyed

cppref says: Rvalue references can be used to extend the lifetimes of temporary objects

Question 1: Why isn't Child destroyed in the very end (or at least after Done)?
Question 2: How to make it live longer?

P.S:

Child& child;
...
Parent(Child c) :child(c)

Gives the exact same result.

Aucun commentaire:

Enregistrer un commentaire