VOOZH about

URL: https://www.geeksforgeeks.org/cpp/move-constructors-in-c-with-examples/

⇱ Move Constructors in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move Constructors in C++

Last Updated : 26 Aug, 2025

A move constructor is a special constructor in C++ that lets us transfer the contents of one object to another without copying the data. It is useful for performance - it's faster than copying.

Syntax of Move Constructor in C++

  • className&& is an rvalue reference to another object of the same class.
  • The double ampersand && is key: it allows the function to bind to temporary (rvalue) objects.
  • The other object is the source from the resource will be moved, not copied.

Example:


Output
Constructor called
Move Constructor called

After move:
obj1: No data
obj2: Value: 42
Destructor deleting data: 42
Destructor called on nullptr

Why Move Constructors are Used?

Move constructors are used to transfer resources (like memory or file handles) from one object to another without making a copy, which makes the program faster and more efficient. They're especially useful when working with temporary objects or large data.

Example: Program with Only Copy Constructor and No Move Constructor


Output
Constructor 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

Example: Program with Move Constructor


Output
Constructor 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

Noexcept Move Constructor

A noexcept move constructor is a move constructor that guarantees it won't throw any exceptions.

Example 1: Without noexcept Move Constructor


Output
Move constructor
Move constructor
Resize happens
Move constructor
Copy constructor
Copy constructor

Example 2: With noexcept Move Constructor


Output
Move constructor 
Move constructor 
Resize happens
Move constructor 
Move constructor 
Move constructor 

Why use noexcept?

  • It helps the compiler optimize our code, especially with STL containers like std::vector.
  • If a move constructor is not marked noexcept, some STL operations will fall back to slower copy operations to avoid potential exceptions.
Comment