Learn C++

Move Assignment Operator in C++ 11

In C++ programming, we have a feature called the move assignment operator, which was introduced in C++11. It helps us handle objects more efficiently, especially when it comes to managing resources like memory. In this article, we will discuss move assignment operators, when they are useful and called, and how to create user-defined move assignment operators.

Move Assignment Operator

The move assignment operator was added in C++ 11 to further strengthen the move semantics in C++. It is like a copy assignment operator but instead of copying the data, this moves the ownership of the given data to the destination object without making any additional copies. The source object is left in a valid but unspecified state.

User-Defined Move Assignment Operator

The programmer can define the move assignment operator using the syntax given below:

As you may have noticed, the move assignment operator function uses a special && reference qualifier. It represents the r-value references (generally literals or temporary values).

Usually, it returns a reference to the object (in this case, *this) so you can chain assignments together.

The move constructor is called by the compiler when the argument is an rvalue reference which can be done by std::move() function. 

Example of Move Assignment Operator

In this program, we will create a dynamic array class and create a user-defined move assignment operator.

Explanation

The move assignment operator (operator=) is used to transfer resources from one DynamicArray object to another. It releases the current resources of the destination object, takes the resources from the source object, and leaves the source object in a valid but unspecified state.

In the main function:

  • We create two DynamicArray objects, arr1 with 5 elements and arr2 with 10 elements. We print their initial states.
  • We use the move assignment operator to transfer the resources from arr1 to arr2 by calling arr2 = std::move(arr1).
  • After the move, we print the states of both arr1 and arr2. arr1 is now in a valid but unspecified state, and arr2 contains the resources of arr1.
Note: We can also define a move constructor with a move assignment operator and reduce the code redundancy by calling the move assignment operator from the move constructor. To know about move constructor, refer to the article – Move Constructors in C++

Implicit Definition of Move Assignment Operator

The compiler also defines a default move assignment operator implicitly when the following conditions are satisfied:

  • No user-defined copy constructor is present.
  • No user-defined destructor is present.
  • No user-defined move constructor is present.

Need of Move Assignment Operator

In C++, objects can manage resources like memory. When we copy an object, it can be quite slow, especially if the object holds a lot of resources. Traditional copy operations create new copies, which can lead to unnecessary memory usage and slow down your program.

This is where move assignment operators come to the rescue. They let one object take over the resources of another, without making extra copies. This can significantly boost performance in scenarios like resizing arrays or returning objects from functions.

In contrast to the copy assignment operator, the end result of the move assignment operator will be a single copy of the source object.

Similar Reads

  • Geeks Premier League
  • Geeks Premier League 2023

Please Login to comment...

Improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

move-constructors-and-move-assignment-operators-cpp.md

Latest commit, file metadata and controls, move constructors and move assignment operators (c++).

This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: && .

This topic builds upon the following C++ class, MemoryBlock , which manages a memory buffer.

The following procedures describe how to write a move constructor and a move assignment operator for the example C++ class.

To create a move constructor for a C++ class

Define an empty constructor method that takes an rvalue reference to the class type as its parameter, as demonstrated in the following example:

In the move constructor, assign the class data members from the source object to the object that is being constructed:

Assign the data members of the source object to default values. This prevents the destructor from freeing resources (such as memory) multiple times:

To create a move assignment operator for a C++ class

Define an empty assignment operator that takes an rvalue reference to the class type as its parameter and returns a reference to the class type, as demonstrated in the following example:

In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself.

In the conditional statement, free any resources (such as memory) from the object that is being assigned to.

The following example frees the _data member from the object that is being assigned to:

Follow steps 2 and 3 in the first procedure to transfer the data members from the source object to the object that is being constructed:

Return a reference to the current object, as shown in the following example:

Example: Complete move constructor and assignment operator

The following example shows the complete move constructor and move assignment operator for the MemoryBlock class:

Example Use move semantics to improve performance

The following example shows how move semantics can improve the performance of your applications. The example adds two elements to a vector object and then inserts a new element between the two existing elements. The vector class uses move semantics to perform the insertion operation efficiently by moving the elements of the vector instead of copying them.

This example produces the following output:

Before Visual Studio 2010, this example produced the following output:

The version of this example that uses move semantics is more efficient than the version that does not use move semantics because it performs fewer copy, memory allocation, and memory deallocation operations.

Robust Programming

To prevent resource leaks, always free resources (such as memory, file handles, and sockets) in the move assignment operator.

To prevent the unrecoverable destruction of resources, properly handle self-assignment in the move assignment operator.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing the move constructor to call the move assignment operator. The following example shows a revised version of the move constructor that calls the move assignment operator:

The std::move function converts the lvalue other to an rvalue.

Rvalue Reference Declarator: && std::move

IMAGES

  1. Chapter 18 Vectors and Arrays

    move constructor move assignment

  2. C++ : How to force std::sort to use move constructor and move

    move constructor move assignment

  3. [Solved] Move Constructor, move vector between two

    move constructor move assignment

  4. Move Constructor/Assignment, Lambdas

    move constructor move assignment

  5. Move constructor and move assignment in C++ (Arabic)

    move constructor move assignment

  6. C++11 : Move constructor & Move Assignment operator

    move constructor move assignment

VIDEO

  1. C++ Tutorial: Rule of 5 [move constructor, move assignment operator]

  2. C++11 : Move constructor & Move Assignment operator

  3. std::move and the Move Assignment Operator in C++

  4. C++ 11 Move Semantics: Move Constructor

  5. Copy and Move Constructors

  6. Move constructor and move assignment in C++ (Arabic)

COMMENTS

  1. Move Constructors and Move Assignment Operators (C++)

    The following example shows the complete move constructor and move assignment operator for the MemoryBlock class:

  2. 22.3

    You can implement the move constructor and move assignment using your own swap function, as long as your swap member function does not call the move constructor or …

  3. Difference between the move assignment operator and move …

    A move constructor is executed only when you construct an object. A move assignment operator is executed on a previously constructed object. It is exactly the same …

  4. Move constructors

    Move constructors typically transfer the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, thread handles, etc.) …

  5. Move assignment operator

    A move assignment operator is a non-template non-static member function with the name operator= that can be called with an argument of the same class type and copies the …

  6. Move Constructors in C++

    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 …

  7. Конструкторы move и операторы присваивания move (C++)

    В этом разделе описывается запись конструктора перемещения и оператора назначения перемещения для класса C++. Конструктор перемещения позволяет …

  8. Move Assignment Operator in C++ 11

    The move assignment operator (operator=) is used to transfer resources from one DynamicArray object to another. It releases the current resources of the destination object, …

  9. move-constructors-and-move-assignment-operators-cpp.md

    This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved …