Move constructor in class definition
I am unable to understand how a move constructor works in this example of code. If someone could break down the process of what is taking place and explain to me on why to use a move constructor.
Code:
class MyString
{
MyString(MyString&& MoveSource)
{
if( MoveSource.Buffer != NULL )
{
Buffer = MoveSource.Buffer; // take ownership i.e. 'move'
MoveSource.Buffer = NULL; // set the move source to NULL i.e. free it
}
}
};
Example from "SamsTeachYourself: C++ in One Hour a Day"
Re: Move constructor in class definition
Quote:
Originally Posted by Zyrion
I am unable to understand how a move constructor works in this example of code. If someone could break down the process of what is taking place
The code looks wrong since the MyString class does not have any member variables, but I assume that it does have a member pointer named Buffer, along with other member functions that were not shown. Presumably, Buffer points to the first character of an array of characters that are the contents of a (null terminated?) string.
If these assumptions are correct, then are you sure you don't understand the implementation of the move constructor? Especially with the comments, it really is quite trivial.
Quote:
Originally Posted by Zyrion
explain to me on why to use a move constructor.
If you don't need to copy because the source object will no longer be used, then a move would be more efficient (or at least no less efficient) than a copy. Consider the corresponding copy constructor: it would have to copy the entire buffer, not just copy a pointer.