A move constructor is a special type of constructor in C++ that is used to create a new object from the already existing object of the same type, but instead of making a copy of it, it makes the new object point to the already existing object in the memory, leaving the source object in a valid but unspecified state.
In this article, we will learn about move constructor, why they are used and how to implement them in our C++ program.
What are Move Constructors?
In C++, move constructors is a type of constructor that works on the r-value references and move semantics (move semantics involves pointing to the already existing object in the memory).
Unlike copy constructors that work with the l-value references and copy semantics(copy semantics means copying the actual data of the object to another object), move constructor transfer the ownership of the already existing object to the new object without making any copy of it. It makes the new object point to the already existing object in the heap memory.
Syntax of Move Constructor in C++
The move constructor takes the rvalue reference to the object of the same class as parameter.
ClassName (ClassName&& obj) {
data = obj.data;
// Nulling out the pointer to the temporary data
obj.data = nullptr;
}We transfer the ownership of the resources from the old object to the new object and nullify the old object pointer.
Example:
Geeks (Geeks&& obj) {
ptr = obj.ptr;
obj.ptr = nullptr;
}Just like any other member function, we can also define the more constructor outside the class.
Example of Move Constructor in C++
C++
// C++ Program to illustrate how to use the move constructor
#include <iostream>
using namespace std;
class Simple {
private:
int* data;
public:
// Constructor
Simple(int value) : data(new int(value))
{
cout << "Constructor called, data = " << *data
<< endl;
}
// Destructor
~Simple()
{
delete data;
cout << "Destructor called" << endl;
}
// Move constructor
Simple(Simple&& other)
: data(other.data)
{
// nullify the other object resource
other.data = nullptr;
cout << "Move constructor called" << endl;
}
// Move assignment operator
Simple& operator=(Simple&& other)
{
if (this != &other) {
delete data; // Free existing resource
data = other.data; // Transfer ownership
other.data = nullptr; // Nullify source
cout << "Move assignment called" << endl;
}
return *this;
}
// Disable copy constructor and copy assignment operator
Simple(const Simple&) = delete;
Simple& operator=(const Simple&) = delete;
// Function to print the value
void print()
{
if (data) {
cout << "Data: " << *data << endl;
}
else {
cout << "Data is null" << endl;
}
}
};
int main()
{
// Create a Simple object with value 42
Simple obj1(42);
obj1.print();
// Move obj1 to obj2 using move constructor
Simple obj2 = move(obj1);
// Print obj2's data
obj2.print();
// Print obj1's data after move
obj1.print();
// Create another Simple object with value 84
Simple obj3(84);
// Move obj2 to obj3 using move assignment
obj3 = move(obj2);
obj3.print();
obj2.print();
return 0;
}
OutputConstructor called, data = 42
Data: 42
Move constructor called
Data: 42
Data is null
Constructor called, data = 84
Move assignment called
Data: 42
Data is null
Destructor called
Destructor called
Destructor called
Why Move Constructors are Used?
Move constructor moves the resources in the heap, i.e., unlike copy constructors which copy the data of the existing object and assigning it to the new object, move constructor just makes the pointer of the declared object to point to the data of temporary object and nulls out the pointer of the temporary objects. Thus, move constructor prevents unnecessarily copying data in the memory. This increase the performance of the program by avoiding the overhead caused by unnecessary copying.
Work of move constructor looks a bit like default member-wise copy constructor but in this case, it nulls out the pointer of the temporary object preventing more than one object to point to same memory location.
Example: Program with Only Copy Constructor and No Move Constructor
C++
// C++ program without declaring the
// move constructor
#include <iostream>
#include <vector>
using namespace std;
// Move Class
class Move {
private:
// Declaring the raw pointer as
// the data member of the class
int* data;
public:
// Constructor
Move(int d)
{
// Declare object in the heap
data = new int;
*data = d;
cout << "Constructor is called for " << d << endl;
};
// Copy Constructor to delegated
// Copy constructor
Move(const Move& source)
: Move{ *source.data }
{
// Copying constructor copying
// the data by making deep copy
cout << "Copy Constructor is called - "
<< "Deep copy for " << *source.data << endl;
}
// Destructor
~Move()
{
if (data != nullptr)
// If the pointer is not
// pointing to nullptr
cout << "Destructor is called for " << *data
<< endl;
else
// If the pointer is
// pointing to nullptr
cout << "Destructor is called"
<< " for nullptr" << endl;
// Free the memory assigned to
// data member of the object
delete data;
}
};
// Driver Code
int main()
{
// Create vector of Move Class
vector<Move> vec;
// Inserting object of Move class
vec.push_back(Move{ 10 });
vec.push_back(Move{ 20 });
return 0;
}
OutputConstructor is called for 10
Constructor is called for 10
Copy Constructor is called - Deep copy for 10
Destructor is called for 10
Constructor is called for 20
Constructor is called for 20
Copy Constructor is called - Deep copy for 20
Constructor is called for 10
Copy Constructor is called - Deep copy for 10
Destructor is called for 10
Destructor is called for 20
Destructor is called for 10
Destructor is called for 20
Explanation
The above program shows the unnecessarily calling copy constructor and inefficiently using the memory by copying the same data several times as it new object upon each call to copy constructor.
This unnecessary use of the memory can be avoided by using move constructor.
Example: Program with Move Constructor
C++
// C++ program for demonstrating the use of
// move constructor
#include <iostream>
#include <vector>
using namespace std;
// Move Class
class Move {
private:
// Declare the raw pointer as
// the data member of class
int* data;
public:
// Constructor
Move(int d)
{
// Declare object in the heap
data = new int;
*data = d;
cout << "Constructor is called for " << d << endl;
};
// Copy Constructor
Move(const Move& source)
: Move{ *source.data }
{
// Copying the data by making
// deep copy
cout << "Copy Constructor is called -"
<< "Deep copy for " << *source.data << endl;
}
// Move Constructor
Move(Move&& source)
: data{ source.data }
{
cout << "Move Constructor for " << *source.data
<< endl;
source.data = nullptr;
}
// Destructor
~Move()
{
if (data != nullptr)
// If pointer is not pointing
// to nullptr
cout << "Destructor is called for " << *data
<< endl;
else
// If pointer is pointing
// to nullptr
cout << "Destructor is called"
<< " for nullptr " << endl;
// Free up the memory assigned to
// The data member of the object
delete data;
}
};
// Driver Code
int main()
{
// Vector of Move Class
vector<Move> vec;
// Inserting Object of Move Class
vec.push_back(Move{ 10 });
vec.push_back(Move{ 20 });
return 0;
}
OutputConstructor is called for 10
Move Constructor for 10
Destructor is called for nullptr
Constructor is called for 20
Move Constructor for 20
Constructor is called for 10
Copy Constructor is called -Deep copy for 10
Destructor is called for 10
Destructor is called for nullptr
Destructor is called for 10
Destructor is called for 20
Explanation:
The unnecessary call to the copy constructor is avoided by making the call to the move constructor. Thus, making the code more memory efficient and decreasing the overhead of calling the move constructor.
Noexcept Move Constructor
Using the noexcept keyword with move constructor guarantees that it will not throw any exceptions during execution. This is one of the optimization that is useful in the following cases:
- Algorithms generally use move constructor where reorder of elements or change in container size require. By marking the move constructor noexcept, we ensure that algorithms can always safely implement moves instead falling back to copying if move fails.
- Some temporary objects are often moved, not copied, so in this case also, we can use noexcept move constructors.
Suppose we have a vector V which contains objects of some class named C. Assume initially vector has size 2 after filling all 2 elements vector needs to grow. So here is one optimization we can do by saying move constructors as noexcept.
When we say move constructor as noexcept we’d say compiler to move the objects whenever it will do the resize operation. In this case compiler will use move rather than using of copy constructor in reallocation phase and by using move constructors we can save a lot of time for copying all objects.
Example 1: Without noexcept Move Constructor
C++
// C++ program to illustrate what happens when we
// don't use the noexcept move constructor
#include <bits/stdc++.h>
using namespace std;
class A {
public:
A() {}
// Move constructor not marked as noexcept
A(A&& other) {
cout << "Move constructor" << endl;
}
// Copy constructor
A(const A& other) {
cout << "Copy constructor" << endl;
}
};
int main() {
vector<A> v;
// Reserve space for at least two elements to
// avoid immediate resizing
v.reserve(2);
// Uses the move constructor for the temporary objects
v.push_back(A());
v.push_back(A());
cout << "Resize happens" << endl;
// Move constructor may be called again if resizing occurs
v.push_back(A());
return 0;
}
OutputMove constructor
Move constructor
Resize happens
Move constructor
Copy constructor
Copy constructor
Explanation
Here, for first two elements, it is quiet simple it’s using move constructor, but for 3rd element vector has to resize itself . For first element, compiler is still try to use move constructor but since it is not marked as noexcept so it might throw an exception , so to make it more exception safe compiler is going to start copy constructor for copying remaining elements.
Example 2: With noexcept Move Constructor
C++
// C++ Program to illustrate the use of
// noexcept move constructor
#include <vector>
#include <iostream>
using namespace std;
class Test {
public:
Test(){}
// Move constructor marked as noexcept
Test(Test&& other) noexcept {
cout << "Move constructor " << endl;
}
// Copy constructor
Test(const Test& other) {
cout << "Copy constructor " << endl;
}
};
int main() {
vector<Test> vec;
vec.reserve(2); // Reserve space for at least two elements
Test a;
vec.push_back(Test());
vec.push_back(Test()); // Uses the move constructor
cout << "Resize happens" << endl;
vec.push_back(Test());
return 0;
}
OutputMove constructor
Move constructor
Resize happens
Move constructor
Move constructor
Move constructor
Explanation
Here, since move constructor is noexcept, we are making sure to copiler that it won’t through any exception, that’s why compiler is safely going to use move constructor instead of copy. By doing this we can operate vector faster
Why It Is Not a Good Practice to Make Copy Constructor as noexcept?
Copy constructors often involve deep copying, which can include resouce allocation by using new, malloc, etc , these can throw exceptions (typically std::bad_alloc). So. even if making it noexcept won’t give any error, it is not a good practice.
MUST READ ARTICLES:
Similar Reads
CamelCase Pattern Matching
Given a list of words where each word follows CamelCase notation, the task is to print all words in the list that matches the given pattern, where the pattern consists of uppercase characters only. A word matches the pattern if all characters of the pattern appear sequentially in the word's uppercas
7 min read
How to Split a String by Multiple Delimiters in C++?
In C++, while working with string manipulation we may sometimes need to split a string into substrings based on multiple delimiters. In this article, we will learn how to split a string by multiple delimiters in C++. For Example, Input: string inputString= "Hello,World;This|is.GeeksForGeeks"; string
3 min read
How Do I Continue to the Next Iteration of a for Loop After an Exception is Thrown in C++?
In C++, when an exception is thrown, the normal flow of the program is disrupted and we need to take care of it. In this article, we will learn how can we continue to the next iteration of a for loop after an exception is thrown in C++. Continue Loop After an Exception is Thrown in C++To continue to
2 min read
Serialize and Deserialize an Object in C++
In C++, serialization is the process of converting an object into a sequence of bytes so that it can be stored in memory or transmitted across a network and deserialization is the reverse process, where the byte stream is used to reconstruct the original object. In this article, we will learn how we
4 min read
Maximum in a 2D matrix using Multi-threading in C++
Given a 2-D matrix, find the element having maximum value using multi-threading. Prerequisite : Multithreading Examples : Input : {{1, 5, 3, 6}, {22, 10, 4, 34}, {4, 45, 67, 3}, {69, 3, 23, 3}} Output :69 Input :{{1, 2, 3} {2, 4, 5}} Output :5 A matrix can be of very large size so when it comes to t
2 min read
valarray tanh() function in C++
The tanh() function is defined in valarray header file. This function is used to calculate hyperbolic tangent of the value of each element in valarray and returns a valarray containing the hyperbolic tangent of all the elements. Syntax: tanh(varr); Parameter: This function takes a mandatory paramete
2 min read
Error Handling in C
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors in the first place and test return values from the functions. A lot of C function calls return -1 or NULL or set an i
8 min read
How to Convert a String to a Char Array in C?
In C, the only difference between the string and a character array is possibly the null character '\0' but strings can also be declared as character pointer in which case, its characters are immutable. In this article, we will learn how to convert a string to a char array in C. The most straightforw
2 min read
rotate() in C++ STL
In C++, rotate() is a built-in function used to rotate the elements of a range in left or right direction such that the element pointed to by a specified iterator becomes the new first element of the range. Let's take a look at an example: [GFGTABS] C++ #include <bits/stdc++.h> using namespace
4 min read
Mean of an Array
Given an array arr[]. The task is to find the mean(floor value) of the array. Examples: Input: arr[] = [1, 3, 4, 2, 6, 5, 8, 7]Output: 4Explanation: Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36, Mean = 36/8 = 4 Input: arr[] = [4, 4, 4, 4, 4]Output: 4Explanation: Sum of the elements is 4
2 min read
Cvent Interview Experience (On campus for Internship and Full Time)
Technical attitude test(Round 1) This round consisted of 30 aptitude questions based on general aptitude and computer science fundamental subjects like operating system, dbms, c/c++, sql, computer networks. Around 300 students sat for this test and 41 students were shortlisted for the next coding ro
4 min read
Precedence of postfix ++ and prefix ++ in C/C++
In C/C++, precedence of Prefix ++ (or Prefix --) has same priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix --) is higher than both Prefix ++ and *. If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right ass
4 min read
C Program to Traverse an Array in Reverse
Write a C program to traverse a given array in reverse order that contains N elements. Examples Input: arr[] = {2, -1, 5, 6, 0, -3}Output: -3 0 6 5 -1 2 Input: arr[] = {4, 0, -2, -9, -7, 1}Output: 1 -7 -9 -2 0 4 Different Ways to Traverse an Array in Reverse Order in CWe can traverse/print the array
2 min read
Longest subsequence consisting of alternate vowels and consonants
Given a non-empty string S, the task is to print the longest subsequence from the string S which contains alternating vowels and consonants. Note: If multiple such subsequences exist having the same length, print the subsequence having the maximum sum of ASCII values of its characters.Examples: Inpu
13 min read
Multimap of tuples in C++ with Examples
What is a multimap? In C++, a multimap is an associative container that is used to store elements in a mapped fashion. Internally, a multimap is implemented as a red-black tree. Each element of a multimap is treated as a pair. The first value is referred to as key and the second value is referred to
6 min read
A nested loop puzzle
Which of the following two code segments is faster? Assume that compiler makes no optimizations. C/C++ Code /* FIRST */ for(i = 0; i < 10; i++) for(j = 0; j < 100; j++) //do something // This code is contributed by Shubham Singh C/C++ Code /* FIRST */ for(i=0;i<10;i++) for(j=0;j<100;j++)
7 min read
Maximum count of sub-strings of length K consisting of same characters
Given a string str and an integer k. The task is to count the occurrences of sub-strings of length k that consist of the same characters. There can be multiple such sub-strings possible of length k, choose the count of the one which appears the maximum number of times as the sub-string (non-overlapp
6 min read
Implicit initialization of variables with 0 or 1 in C
In C programming language, the variables should be declared before a value is assigned to it. For Example: // declaration of variable a and // initializing it with 0. int a = 0; // declaring array arr and initializing // all the values of arr as 0. int arr[5] = {0}; However, variables can be assigne
2 min read
Check if the given graph represents a Ring Topology
Given a graph G, the task is to check if it represents a Ring Topology.A Ring Topology is the one shown in the image below: Examples: Input : Graph = Output : YES Input : Graph = Output : NO A graph of V vertices represents a Ring topology if it satisfies the following three conditions: Number of ve
11 min read