• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Misery

Is using std::move() necessary?

12 posts in this topic

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):
[code]
Matrix Multiply(const Matrix &A, const Matrix &B)
{
Matrix C;
C.Resize(A.Rows,B.Cols);
//perform actions
return std::move(C); //(1)
}
[/code]

Both move constructor and move operator is used. But when I use instead (1) just:
[code]
return C;
[/code]
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.
0

Share this post


Link to post
Share on other sites
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.

[code]
Matrix Multiply(const Matrix &A, const Matrix &B)
[/code]
This will return a temporary copy of a Matrix.

[code]
return std::move(C);
return static_cast<Matrix&&>(C);
return Matrix(static_cast<Matrix&&>(C));
[/code]
Each of these should cast C to rvalue reference (an unnamed temporary) and call the move constructor of Matrix class, and return that instance.

[code]
return C;
return Matrix(C);
[/code]
These should call the copy constructor (in debug build with all optimizations off). [b]See Matt-D's reply below for correction.[/b]

[code]
Matrix result = Multiply(a, b);
[/code]
This should call the default constructor, and then move assignment operator with the returned temporary.

[code]
Matrix result(Multiply(a, b));
[/code]
This should call the move[b] constructor[/b] with the returned temporary.

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

edit: Edit in bold. Edited by Codarki
1

Share this post


Link to post
Share on other sites
[b]@Codarki[/b]: 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
0

Share this post


Link to post
Share on other sites
[quote name='Codarki' timestamp='1342688874' post='4960854']
return C;
These should call the copy constructor (in debug build with all optimizations off)
[/quote]
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: [url="http://stackoverflow.com/a/9532647/859774"]http://stackoverflow.../9532647/859774[/url] Edited by Matt-D
1

Share this post


Link to post
Share on other sites
[quote name='Matt-D' timestamp='1342688670' post='4960852']
Not only never necessary, but a bad idea on function return (it may inhibit copy elision / RVO)
[/quote]
Seems like you're right.

[quote name='Matt-D' timestamp='1342688670' post='4960852']
See also "Moving from lvalues" and "Moving out of functions" here:
[url="http://stackoverflow.com/a/11540204/859774"]http://stackoverflow...11540204/859774[/url]
[/quote]
Very good explanation.

[quote name='Codarki' timestamp='1342688874' post='4960854']
return C;
return Matrix(C);
These should call the copy constructor (in debug build with all optimizations off)
[/quote]

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, [b]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[/b]. 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.
1

Share this post


Link to post
Share on other sites
Codarki: yup :-)

Misery:

[quote name='Misery' timestamp='1342689643' post='4960858']
When and how do I use std::move() properly?
[/quote]

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) [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]

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":
[url="http://stackoverflow.com/a/11540204/859774"]http://stackoverflow...11540204/859774[/url] // 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: [url="http://pizer.wordpress.com/2009/04/13/c0x-do-people-understand-rvalue-references/"]http://pizer.wordpre...lue-references/[/url]

Another case is for moving-in:
int b = f( std::move(x) ); // OK, explicit move
// See discussion here: [url="http://cpp-next.com/archive/2009/09/making-your-next-move/"]http://cpp-next.com/...your-next-move/[/url]

Compare the moving-in vs copying-in examples here: [url="http://stackoverflow.com/a/6638485/859774"]http://stackoverflow.../6638485/859774[/url]

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:
[url="http://www2.research.att.com/~bs/terminology.pdf"]http://www2.research...terminology.pdf[/url]
[url="http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues"]http://stackoverflow...es-and-prvalues[/url]
[url="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3055.pdf"]http://www.open-std..../2010/n3055.pdf[/url]
[url="http://en.cppreference.com/w/cpp/language/value_category"]http://en.cppreferen.../value_category[/url]
[url="http://blog.natekohl.net/rvalue-references-and-rvalues/"]http://blog.natekohl...es-and-rvalues/[/url]
[url="http://akrzemi1.wordpress.com/2011/11/09/lvalues-rvalues-and-references/"]http://akrzemi1.word...and-references/[/url] Edited by Matt-D
2

Share this post


Link to post
Share on other sites
Thanks a lot :]
Your answers let some light into dungeons of my programming adventure [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
1

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites
Another thing to keep in mind is [i]why[/i] 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.
0

Share this post


Link to post
Share on other sites
[b]@Brother Bob[/b]: 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 [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
0

Share this post


Link to post
Share on other sites
[b]@Zoomulator[/b]: That is the case, making the long story short, the matrix looks like this:
[code]
template <class DATA_TYPE,INT_TYPE>
class Matrix{
private:
DATA_TYPE *Data;
INT_TYPE Rows,Cols;
public:
//all the stuff
};
[/code] Edited by Misery
1

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0