Search code examples
c++movebase-class

Is it OK to move from r-value reference to sub-object of temporary?


If a temporary Derived is passed to a method that takes a Base&&, is it OK to move-construct Base from that?


Solution

  • The temporaries lifetime is extended until the end of the function (or the lifetime of the parameter, respectively), so you can move construct a Base object from that reference.

    Note that you need an additional std::move to make it a move and not a copy:

    Base b = std::move(param);
    

    The temporary object you move from is left in whatever state is specified for moved-from object of its type. Standard library types like vector<int> or string have a so-called "valid but unspecified state" -- basically the only sensible operations you can do are assign (that is, copy or move into it) or destroy it. Without information about Base' move constructor definition no further assumptions can be made.