Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expensive to move types

Tags:

c++

rvo

I am reading the official CPPCoreGuidelines to understand correctly when it's reliable to count on RVO and when not. At F20 it is written:

If a type is expensive to move (e.g., array), consider allocating it on the free store and return a handle (e.g., unique_ptr), or passing it in a reference to non-const target object to fill (to be used as an out-parameter)

I understand that the non-STL types are not optimized to move, but how can I easy detect other types expensive to move, so I will not use RVO on them?

like image 673
Taw Avatar asked Nov 12 '17 13:11

Taw


1 Answers

You seem to have misunderstood what "RVO" is. "RVO" stands for "return value optimization" and it's a compiler optimization that prevents any move or copy constructor from being invoked. E.g.

std::vector<huge_thing> foo()
{
    std::vector<huge_thing> result{/* ... */};
    return result;
}

void bar()
{
    auto v = foo(); // (0)
}

Any decent compiler will not execute any copy/move operation and simply construct v in place at (0). In C++17, this is mandatory thanks to the changes to prvalues.


In terms of expensive moves: sure, there can be types expensive to move - but I cannot think of any instance where a move would be more expensive than a copy.

Therefore:

  • Rely on RVO, especially in C++17 - this does not incur any cost even for types "expensive to move".

  • If a type is expensive to move, it's also expensive to copy - so you don't really have a choice there. Redesign your code so that you don't need the copy/move if possible.

like image 51
Vittorio Romeo Avatar answered Oct 28 '22 11:10

Vittorio Romeo