c++movervalue-reference

Lifetime of rvalue of custom class bound by rvalue reference


#include <iostream>

using namespace std;

class Someclass
{
    public:
    
    ~Someclass()
    {
        cout << "Someclass Dtor called" << endl;
    }
};

int main()
{
    Someclass obj;
    
    {
        Someclass&& ref = move(obj);
    }

    // At this point why the dtor is not called ? Because the reference went out of scope
    
    cout << "Ending program" << endl;
    
    return 0;
}

In the above code the output is as follows:

Ending program

Someclass Dtor called

But my query is why the output is not this ?

Someclass Dtor called

Ending program

When the reference is going out of scope, should it not invoke dtor of Someclass?


Solution

  • why the output is not this ?

    Because no move operation(move construction/assignment) happens. in your example since ref is an rvalue reference. Basically, std::move(obj) just gives an xvalue which is then bound to the rvalue ref ref.

    ref is still just an alias for the actual object obj whose lifetime only ends after the } of the main.


    If you were to remove the && from ref, then you would observe your expected output because in this case move operation does happen:

    {
    //-----------vv----------------> && removed from here
        Someclass ref = move(obj);
    }
    

    The output of the above modified program will be:

    Someclass Dtor called
    Ending program
    Someclass Dtor called
    

    Demo