Typically, C ++ encoders explicitly move explicitly or simply rely on the compiler to do this?

We have this in some function:

BigClass big; // prepare big somehow OtherClass foo(std::move(big), maybe, other, params); // know that we won't be using "big" after this. 

Will most C ++ encoders really move there these days to guarantee progress?

+7
source share
3 answers

In your particular piece of code, you either move directly or you won’t move at all. The compiler will never exit lvalue (this is not eXpiring).

+10
source

I would put std::move there so that there is movement, because otherwise it will not be. :)

Alternative is

 auto MakeBig = [&]()->BigClass { BigClass big; //prepare big somehow return big; // must be a `move`, if not elided! }; OtherClass foo(MakeBig(), maybe, other, params); 

or, if you are not weak in heart:

 OtherClass foo([&]()->BigClass { BigClass big; //prepare big somehow return big; // must be a `move`, if not elided! }(), maybe, other, params); 

where we end up creating big up in lambda and then defer creation. This does not always work, mind you.

The advantage of this pattern is that the move can be undone if foo takes its first argument by value, and taking by value is now the right way to do this for the move class, which OtherClass will copy anyway. If it does not accept its first argument by value, the temporary one created to build foo can still be deleted, so only one move will happen (between the temporary and foo ).

+1
source

If you use C ++ 11, sometimes the compiler will make moves for you (R-Value links), but if you want to explicitly move a large object, then yes, you must explicitly "move" it with

 std::move 

Additional Information

0
source

All Articles