0

so I have this dummy code, which essentially just does the job of a c++ string object:

#include <iostream>
#include <string>
#include <array>
#include <cstring>

using namespace std;

class MyString {
private:
    char* buffer;
public:
    MyString(const char* initString){//constructor

        cout << "Invoking constructor" << endl;

        buffer  = NULL; //intialize member var

        if(initString != NULL){
            buffer = new char [strlen(initString) + 1];//allocate memory for the object 
            strcpy(buffer, initString);//copy the string value to the block of memory

            cout << "buffer points to 0x" << hex << (unsigned int*)buffer << endl;

        }
    }

    MyString(const MyString& copySource) {
        buffer = NULL;

        cout << "Copy constructor initiated" << endl;

        if(copySource.buffer != NULL) {

            buffer = new char [strlen(copySource.buffer) + 1];//copy object and allocate new memory for it

            strcpy(buffer, copySource.buffer);

            cout << "buffer points to-> 0x" <<  hex << (unsigned int*)buffer << endl;
        }

    }

    MyString(MyString&& moveSource){//<------

        cout << "Invoked move constructor for " << moveSource.buffer << endl;

        if(moveSource.buffer != NULL){
            buffer = moveSource.buffer; //take ownership i.e "move"
            moveSource.buffer = NULL; //set the move source to NULL
        }
    }

    ~MyString(){ //cannot be overloaded
        cout << "Invoking destructor" << endl;
        delete[] buffer; 
    }

    inline int GetLength(){
        return strlen(buffer); 
    }

    inline const char* GetString(){
        return buffer;
    }

};


MyString Copy(MyString& source) 
{
    MyString copyForReturn(source.GetString()); 
    return copyForReturn;
}

int main(int argc, char const *argv[])
{
        MyString sayHello("Hello");
        MyString sayHelloAgain(Copy(sayHello)); //here Copy(sayHello) is the same as if

    return 0;
}

So I'm learning about move constructors and I was wondering what did the move constructor do that the copy constructor didn't, in this example it assigns the value of the moveSource buffer to the classes own buffer and "it takes ownership of the object", I don't really understand why does it take ownership?, isn't it a shallow copy of the original object?. Also why isn't the copy constructor aswell as the move constructor not invoked here, I can only see in the output two constructors aswell as two destructors being invoked. Thanks in advance.

  • Very closely related, if not a duplicate: https://stackoverflow.com/q/3106110/10077 – Fred Larson Feb 17 '20 at 22:35
  • How many dynamic memory allocations happen in the move constructor vs in the copy constructor? Dynamic memory allocations are expensive, so if we can avoid them by using a move (a transfer of managed resources from an object that's about to be destroyed) then we should. – JohnFilleau Feb 17 '20 at 22:36

0 Answers0