Move constructor in class definition
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Move constructor in class definition

  1. #1
    Join Date
    Apr 2013
    Posts
    6

    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"

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,323

    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.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center