Search code examples
c++move-semanticscopy-assignmentmove-assignment-operator

Are temporary lvalues a use case for std::move


I have a class like this:

class Widget
{
public:
    Widget(A const& a) { /* do something */ }
    Widget(A&& a) { /* do something */ }
};

Which I can use like this:

A a{};
Widget widget{a};

If I came to the conclusion that I don't need a any longer, I could call:

Widget{std::move(a)};

But now what if I needed an A object only for the construction of widget? Would I do this:

Widget widget{A{}};

or

Widget widget{std::move(A{})}; 

Solution

  • A temporary is an rvalue; there are no "temporary lvalues". Widget widget{A{}}; will call Widget(A&& a) as A{} is a temporary. std::move is used when you have an lvalue and you want to make it an rvalue like you do with:

    A a{};
    Widget widget{std::move(a)};
    

    Another reason to use it would be if you are in a function that takes an rvalue and you want to move it to the constructor. With the function

    Widget foo(A&& a);
    

    a is a lvalue in the body of the function. If you want to convert it back to an rvalue then you would need to use std::move like

    Widget foo(A&& a)
    {
        Widget widget{std::move(a)};
    }