Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I move a callee's return value if I'm going to construct an object with it?

class Item { };

class Wrapper
{
    Item i;
    Wrapper(const Item& mI) : i{mI} { }
    Wrapper(Item&& mI) : i{std::move(mI)} { }
};

Item createItem()
{
    Item result;
    // ...
    return result; // No `std::move` needed here
}

Wrapper createWrapper()
{
    Wrapper result{createItem()}; // `std::move(createItem())` ?
    return result;
}

createItem() returns efficiently without having to call std::move.

createWrapper() uses the return value of createItem() and wants to call the Wrapper::Wrapper(Item&&) constructor.

Is it necessary to to use Wrapper result{std::move(createItem())}; or will Wrapper result{createItem()}; suffice?

like image 542
Vittorio Romeo Avatar asked Feb 12 '23 21:02

Vittorio Romeo


1 Answers

There's no need for std::move here. The value of a function call expression is already an rvalue.

like image 69
Mike Seymour Avatar answered Feb 16 '23 02:02

Mike Seymour