Open In App

How to Define a Move Constructor in C++?

In C++, we have a move constructor which is a part of C++11 move semantics and is used to handle resources for temporary and rvalue objects. In this article, we will learn how to write a move constructor in C++.

How to Write Move Constructor in C++?

The move constructor is defined similarly to a copy constructor, but it takes an rvalue reference (Type&&) to the object’s class type as its parameter. To define a move constructor in C++ use the below syntax:



Syntax to Define Move Constructor in C++

className(className&& source) noexcept;

Here,

C++ Program to Define Move Constructor

The below example shows how can we write a move constructor and use it in C++.






// C++ program to declare move constructor
#include <iostream>
#include <vector>
using namespace std;
  
// Move Class
class moveClass {
private:
    // Declaring the raw pointer
    int* p;
  
public:
    // Default Constructor
    moveClass(int d)
    {
        // Declaring object in the heap
        p = new int;
        *p = d;
        cout << "Default Constructor is called for " << d
             << endl;
    };
  
    // Move Constructor
    moveClass(moveClass&& source)
        : p{ source.p }
    {
  
        cout << "Move Constructor is called for "
             << *source.p << endl;
        source.p = nullptr;
    }
  
    // Destructor
    ~moveClass()
    {
        cout << "Destructor invoked!\n";
  
        // Free up the memory assigned to
        // The data member of the object
        delete p;
    }
};
  
int main()
{
    // Vector of Move Class
    vector<moveClass> vec;
  
    // Inserting Object of Move Class
    vec.push_back(moveClass{ 10 });
    return 0;
}

Output
Default Constructor is called for 10
Move Constructor is called for 10
Destructor invoked!
Destructor invoked!


Article Tags :