Jump to content

  • Log In with Google      Sign In   
  • Create Account


Is using std::move() necessary?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 Misery   Members   -  Reputation: 247

Like
0Likes
Like

Posted 19 July 2012 - 01:32 AM

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.

Sponsor:

#2 Matt-D   Crossbones+   -  Reputation: 1405

Like
5Likes
Like

Posted 19 July 2012 - 03:04 AM

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

Edited by Matt-D, 19 July 2012 - 04:10 AM.


#3 Codarki   Members   -  Reputation: 462

Like
1Likes
Like

Posted 19 July 2012 - 03:07 AM

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.

Edited by Codarki, 19 July 2012 - 03:40 AM.


#4 Misery   Members   -  Reputation: 247

Like
0Likes
Like

Posted 19 July 2012 - 03:20 AM

@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?

Edited by Misery, 19 July 2012 - 03:23 AM.


#5 Matt-D   Crossbones+   -  Reputation: 1405

Like
1Likes
Like

Posted 19 July 2012 - 03:23 AM

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

Edited by Matt-D, 19 July 2012 - 03:24 AM.


#6 Codarki   Members   -  Reputation: 462

Like
1Likes
Like

Posted 19 July 2012 - 03:24 AM

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©;
These should call the copy constructor (in debug build with all optimizations off)


Ah this was wrong. C++ standard has special rule:


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.


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

#7 Matt-D   Crossbones+   -  Reputation: 1405

Like
2Likes
Like

Posted 19 July 2012 - 03:38 AM

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) Posted Image

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/

Edited by Matt-D, 19 July 2012 - 04:05 AM.


#8 Misery   Members   -  Reputation: 247

Like
1Likes
Like

Posted 19 July 2012 - 03:44 AM

Thanks a lot :]
Your answers let some light into dungeons of my programming adventure Posted Image

#9 Brother Bob   Moderators   -  Reputation: 7406

Like
1Likes
Like

Posted 19 July 2012 - 04:09 AM

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.

#10 Zoomulator   Members   -  Reputation: 269

Like
0Likes
Like

Posted 19 July 2012 - 04:32 AM

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.

#11 Misery   Members   -  Reputation: 247

Like
0Likes
Like

Posted 19 July 2012 - 04:32 AM

@Brother Bob: At the very moment of your answer, then it helped me very very much, because I didn't even know about move constructors and assignment operators. Thanks to you I really pushed forward my lib, because I was able to choose the philosophy for the class/function interfaces. And I am very grateful for your help. And now replacing std::move to " " in a few files is not a big problem Posted Image

#12 Misery   Members   -  Reputation: 247

Like
1Likes
Like

Posted 19 July 2012 - 04:36 AM

@Zoomulator: That is the case, making the long story short, the matrix looks like this:
template <class DATA_TYPE,INT_TYPE>
class Matrix{
private:
   DATA_TYPE *Data;
   INT_TYPE Rows,Cols;
public:
  //all the stuff
};

Edited by Misery, 19 July 2012 - 04:37 AM.


#13 Zoomulator   Members   -  Reputation: 269

Like
0Likes
Like

Posted 19 July 2012 - 05:35 AM

Then it would indeed make sense to move it.

Just a side note about that though. If you're doing this to make use of move semantics and gain performance, you might actually not get much out of it. The indirection caused by the pointer may actually take more time due to cache misses than copying a small matrix, like 4x4, that's already present in the cache. The performance would be obvious in larger matrices of course. I recommend you do some tests, if this is for optimization.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS