std::move explained with simple example

std::move is a C++11(Introduction to C++11) utility function which is used to convert an lvalue to rvalue expression to forcefully call the move constructor or move assignment operator which will improve the program’s performance drastically. This utility function is only change lvalue into rvalue expression that’s it. This function doesn’t do any kind of memory movement.

Implementation of this function is as follows:

From C++11 onwards:

template< class T >
typename std::remove_reference<T>::type&& move( T&& t );

From C++14 onwards:

template< class T >
constexpr typename std::remove_reference<T>::type&& move( T&& t );

Let’s take an example of usage of this move function:

#include <iostream>
#include <string.h>
 
class MoveHelper
{
private:
    int length;
    char* data;
 
public:
    // Normal Constructor
    MoveHelper(int length, char* sampleData) : length(length)
    {
        cout << "Inside MoveHelper constructor" << endl;
        data = new char[(strlen(sampleData))];
        copy(sampleData, (sampleData + strlen(sampleData)), data);
    }
 
    //Copy Constructor
    MoveHelper(const MoveHelper& copy)
    {
        cout << "Inside MoveHelper copy constructor" << endl;
        length = copy.length;
        data = new char[(strlen(copy.data))];
        std::copy(copy.data, (copy.data + strlen(copy.data)), data);
    }
 
    //Move Constructor
    MoveHelper(MoveHelper&& copy)
    {
        cout << "Inside MoveHelper move constructor" << endl;
        length = copy.length;
        data = copy.data;
        copy.data = NULL;
    }
 
    //destructor
    ~MoveHelper()
    {
        cout << "Inside MoveHelper destructor" << endl;
        delete[] data;
    }
};
 
int main()
{
    MoveHelper mv1(strlen("Hello1234567"), "Hello1234567");
    MoveHelper mv2(mv1); //Copy constructor called
    MoveHelper mv3(move(mv1)); // Move constructor called. After this "mv1" will become useless so don't use this object after this.
}

As shown above “move constructor” is faster than “copy constructor” as move constructor is using “char *” of object “mv1” to object “mv3”. Because of this performance of move constructor is better than copy constructor. Note that after “mv3” object creation, “mv1” object becomes useless and it should not be used anywhere else.

more details related to move constructor

Output of above function:

Inside MoveHelper constructor
Inside MoveHelper copy constructor
Inside MoveHelper move constructor
Inside MoveHelper destructor
Inside MoveHelper destructor
Inside MoveHelper destructor

Leave a Reply

Your email address will not be published. Required fields are marked *