How to Define a Move Constructor in C++?
Last Updated :
01 Mar, 2024
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,
- className is the name of our class.
&&
indicates an rvalue reference to classname
and source
is the source object from which resources are being moved.
- noexcept specifier is used to indicate that the move constructor does not throw exceptions.
C++ Program to Define Move Constructor
The below example shows how can we write a move constructor and use it in C++.
C++
#include <iostream>
#include <vector>
using namespace std;
class moveClass {
private :
int * p;
public :
moveClass( int d)
{
p = new int ;
*p = d;
cout << "Default Constructor is called for " << d
<< endl;
};
moveClass(moveClass&& source)
: p{ source.p }
{
cout << "Move Constructor is called for "
<< *source.p << endl;
source.p = nullptr;
}
~moveClass()
{
cout << "Destructor invoked!\n" ;
delete p;
}
};
int main()
{
vector<moveClass> vec;
vec.push_back(moveClass{ 10 });
return 0;
}
|
Output
Default Constructor is called for 10
Move Constructor is called for 10
Destructor invoked!
Destructor invoked!
Share your thoughts in the comments
Please Login to comment...