Is using std::move() necessary?

Started by
11 comments, last by Zoomulator 11 years, 9 months ago
Hi there,

I have created a Matrix class that does some basic math and such stuff. This class has defined copy and move constructors and operators.
What I have noticed is that when I use syntax like (for example):

Matrix Multiply(const Matrix &A, const Matrix &B)
{
Matrix C;
C.Resize(A.Rows,B.Cols);
//perform actions
return std::move(C); //(1)
}


Both move constructor and move operator is used. But when I use instead (1) just:

return C;

only move operator is used. Which approach is valid? Why call two functions (constructor and operator) if one can call only one?

Thanks and Regards.
Advertisement
Not only never necessary, but also a bad idea for function returning automatic variable such as "C" (it may inhibit copy elision / RVO):
http://stackoverflow...turn-statements
http://stackoverflow...ntics-confusion
http://pizer.wordpre...lue-references/

See also "Moving from lvalues" and "Moving out of functions" here:
http://stackoverflow...11540204/859774
I'm assuming you have tested this in debug build. I also assume when you say move operator, you mean move assignment operator.

I hope someone will correct me for any mistakes.


Matrix Multiply(const Matrix &A, const Matrix &B)

This will return a temporary copy of a Matrix.


return std::move(C);
return static_cast<Matrix&&>(C);
return Matrix(static_cast<Matrix&&>(C));

Each of these should cast C to rvalue reference (an unnamed temporary) and call the move constructor of Matrix class, and return that instance.


return C;
return Matrix(C);

These should call the copy constructor (in debug build with all optimizations off). See Matt-D's reply below for correction.


Matrix result = Multiply(a, b);

This should call the default constructor, and then move assignment operator with the returned temporary.


Matrix result(Multiply(a, b));

This should call the move constructor with the returned temporary.

In release build all of these should optimize to basically nothing.

edit: Edit in bold.
@Codarki: so actually I just should leave bare return C; and optimizations should work in Release mode?
On Linux GCC g++ compiler in Release mode return std::move( ) calls both move constructor and move assignment operator.
Bare return C; calls (regardless to compilation mode) move assignment operator only.

So I deduce, that it is much better not to use std::move() as it doesn't allow compiler to do the proper optimizations. Am I right?
So, the other question:
When and how do I use std::move() properly?

return C;
These should call the copy constructor (in debug build with all optimizations off)

No (assuming "C" is a function local automatic variable, just like in the OP), the standard demands the attempt to automatically treat the object "C" as if it was an rvalue (and thus the move ctor to be called here -- or, if we enable optimizations, copy elision may occur, which is even better than moving), see again: http://stackoverflow.../9532647/859774

Not only never necessary, but a bad idea on function return (it may inhibit copy elision / RVO)

Seems like you're right.


See also "Moving from lvalues" and "Moving out of functions" here:
http://stackoverflow...11540204/859774

Very good explanation.


return C;
return Matrix(C);
These should call the copy constructor (in debug build with all optimizations off)


Ah this was wrong. C++ standard has special rule:
[quote name='§12.8 [class.copy] p32']
When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [ Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided.
[/quote]

This means it will first try to move, and then copy. I wonder if copy constructor has side effects, it might bite someone.
Codarki: yup :-)

Misery:


When and how do I use std::move() properly?


In short: sometimes it has to be used (e.g., unique_ptr example), sometimes it can be used to enable move optimizations (e.g., some moving-out and moving-in cases), sometimes it shouldn't be used (e.g., some moving-out cases, just like in your example where it disables copy elision), sometimes it can't be used (e.g., non-moveable objects) biggrin.png

For a longer version, see "Moving from lvalues" (demonstrating where it has to be used for std::unique_ptr), "Moving into members", "Implementation of move":
http://stackoverflow...11540204/859774 // linked before

While it's not necessary (and bad, as mentioned before) for moving-out automatics (as in your OP), it's appropriate (and good) for moving-out non-automatics:
[source lang="cpp"]string operator+(string && a, string const& b)
{
a += b;
return move(a);
}
[/source]
// See discussion here: http://pizer.wordpre...lue-references/

Another case is for moving-in:
int b = f( std::move(x) ); // OK, explicit move
// See discussion here: http://cpp-next.com/...your-next-move/

Compare the moving-in vs copying-in examples here: http://stackoverflow.../6638485/859774

BTW, it may also be useful to know and understand the "new" value terminology (e.g., the "xvalue" term is used in the above references) -- it's inextricably tied to move semantics and personally was quite helpful to me when trying to understand this topic:
http://www2.research...terminology.pdf
http://stackoverflow...es-and-prvalues
http://www.open-std..../2010/n3055.pdf
http://en.cppreferen.../value_category
http://blog.natekohl...es-and-rvalues/
http://akrzemi1.word...and-references/
Thanks a lot :]
Your answers let some light into dungeons of my programming adventure smile.png
A lot of great resources here.

Misery, I just wanted to drop in and admit (and apologize too of course) that I remember answering one of your questions earlier about returning copy-expensive values and while I did introduce move semantics to you, I also said you had to move() the result. I couldn't find much useful information about rvalue references so my self-taught knowledge from experimenting suggested that was the case. Obviously, I screwed up that testing somewhere and got the wrong impression :)

Matt, your link collection in your first post was quite nice and did clear some small things up a little for me.
Another thing to keep in mind is why you'd want to move it. If your matrix class is flat and contains the data itself, there's no point in moving it.

Moving for optimization's sake only ever makes sense when a class holds pointers to data that it owns on the heap. In such case the move result in only the pointer being moved and thus the heap data stays put and is now owned by the newly located object. In comparison: a proper copy/assignment operation should copy all the data pointed to as well.

But if the class contains all its data directly it will have to move (copy really) each value in the class to the new location anyway. It's the same procedure whether you copy it or not and you wont get any performance gain. Only reason to use move in this case would be to make absolutely sure that the data is unique to one instance, but since it's a matrix class this wouldn't make sense.

This topic is closed to new replies.

Advertisement