This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Move Constructors and Move Assignment Operators (C++)

  • 9 contributors

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

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Learn C++

22.3 — Move constructors and move assignment

In lesson 22.1 -- Introduction to smart pointers and move semantics , we took a look at std::auto_ptr, discussed the desire for move semantics, and took a look at some of the downsides that occur when functions designed for copy semantics (copy constructors and copy assignment operators) are redefined to implement move semantics.

In this lesson, we’ll take a deeper look at how C++11 resolves these problems via move constructors and move assignment.

Recapping copy constructors and copy assignment

First, let’s take a moment to recap copy semantics.

Copy constructors are used to initialize a class by making a copy of an object of the same class. Copy assignment is used to copy one class object to another existing class object. By default, C++ will provide a copy constructor and copy assignment operator if one is not explicitly provided. These compiler-provided functions do shallow copies, which may cause problems for classes that allocate dynamic memory. So classes that deal with dynamic memory should override these functions to do deep copies.

Returning back to our Auto_ptr smart pointer class example from the first lesson in this chapter, let’s look at a version that implements a copy constructor and copy assignment operator that do deep copies, and a sample program that exercises them:

In this program, we’re using a function named generateResource() to create a smart pointer encapsulated resource, which is then passed back to function main(). Function main() then assigns that to an existing Auto_ptr3 object.

When this program is run, it prints:

(Note: You may only get 4 outputs if your compiler elides the return value from function generateResource())

That’s a lot of resource creation and destruction going on for such a simple program! What’s going on here?

Let’s take a closer look. There are 6 key steps that happen in this program (one for each printed message):

  • Inside generateResource(), local variable res is created and initialized with a dynamically allocated Resource, which causes the first “Resource acquired”.
  • Res is returned back to main() by value. We return by value here because res is a local variable -- it can’t be returned by address or reference because res will be destroyed when generateResource() ends. So res is copy constructed into a temporary object. Since our copy constructor does a deep copy, a new Resource is allocated here, which causes the second “Resource acquired”.
  • Res goes out of scope, destroying the originally created Resource, which causes the first “Resource destroyed”.
  • The temporary object is assigned to mainres by copy assignment. Since our copy assignment also does a deep copy, a new Resource is allocated, causing yet another “Resource acquired”.
  • The assignment expression ends, and the temporary object goes out of expression scope and is destroyed, causing a “Resource destroyed”.
  • At the end of main(), mainres goes out of scope, and our final “Resource destroyed” is displayed.

So, in short, because we call the copy constructor once to copy construct res to a temporary, and copy assignment once to copy the temporary into mainres, we end up allocating and destroying 3 separate objects in total.

Inefficient, but at least it doesn’t crash!

However, with move semantics, we can do better.

Move constructors and move assignment

C++11 defines two new functions in service of move semantics: a move constructor, and a move assignment operator. Whereas the goal of the copy constructor and copy assignment is to make a copy of one object to another, the goal of the move constructor and move assignment is to move ownership of the resources from one object to another (which is typically much less expensive than making a copy).

Defining a move constructor and move assignment work analogously to their copy counterparts. However, whereas the copy flavors of these functions take a const l-value reference parameter (which will bind to just about anything), the move flavors of these functions use non-const rvalue reference parameters (which only bind to rvalues).

Here’s the same Auto_ptr3 class as above, with a move constructor and move assignment operator added. We’ve left in the deep-copying copy constructor and copy assignment operator for comparison purposes.

The move constructor and move assignment operator are simple. Instead of deep copying the source object (a) into the implicit object, we simply move (steal) the source object’s resources. This involves shallow copying the source pointer into the implicit object, then setting the source pointer to null.

When run, this program prints:

That’s much better!

The flow of the program is exactly the same as before. However, instead of calling the copy constructor and copy assignment operators, this program calls the move constructor and move assignment operators. Looking a little more deeply:

  • Res is returned back to main() by value. Res is move constructed into a temporary object, transferring the dynamically created object stored in res to the temporary object. We’ll talk about why this happens below.
  • Res goes out of scope. Because res no longer manages a pointer (it was moved to the temporary), nothing interesting happens here.
  • The temporary object is move assigned to mainres. This transfers the dynamically created object stored in the temporary to mainres.
  • The assignment expression ends, and the temporary object goes out of expression scope and is destroyed. However, because the temporary no longer manages a pointer (it was moved to mainres), nothing interesting happens here either.

So instead of copying our Resource twice (once for the copy constructor and once for the copy assignment), we transfer it twice. This is more efficient, as Resource is only constructed and destroyed once instead of three times.

Related content

Move constructors and move assignment should be marked as noexcept . This tells the compiler that these functions will not throw exceptions.

We introduce noexcept in lesson 27.9 -- Exception specifications and noexcept and discuss why move constructors and move assignment are marked as noexcept in lesson 27.10 -- std::move_if_noexcept .

When are the move constructor and move assignment called?

The move constructor and move assignment are called when those functions have been defined, and the argument for construction or assignment is an rvalue. Most typically, this rvalue will be a literal or temporary value.

The copy constructor and copy assignment are used otherwise (when the argument is an lvalue, or when the argument is an rvalue and the move constructor or move assignment functions aren’t defined).

Implicit move constructor and move assignment operator

The compiler will create an implicit move constructor and move assignment operator if all of the following are true:

  • There are no user-declared copy constructors or copy assignment operators.
  • There are no user-declared move constructors or move assignment operators.
  • There is no user-declared destructor.

The implicit move constructor and implicit move assignment operator both do a memberwise move. That is, each member of the moved-from object is moved to the moved-to object.

The key insight behind move semantics

You now have enough context to understand the key insight behind move semantics.

If we construct an object or do an assignment where the argument is an l-value, the only thing we can reasonably do is copy the l-value. We can’t assume it’s safe to alter the l-value, because it may be used again later in the program. If we have an expression “a = b” (where b is an lvalue), we wouldn’t reasonably expect b to be changed in any way.

However, if we construct an object or do an assignment where the argument is an r-value, then we know that r-value is just a temporary object of some kind. Instead of copying it (which can be expensive), we can simply transfer its resources (which is cheap) to the object we’re constructing or assigning. This is safe to do because the temporary will be destroyed at the end of the expression anyway, so we know it will never be used again!

C++11, through r-value references, gives us the ability to provide different behaviors when the argument is an r-value vs an l-value, enabling us to make smarter and more efficient decisions about how our objects should behave.

Key insight

Move semantics is an optimization opportunity.

Move functions should always leave both objects in a valid state

In the above examples, both the move constructor and move assignment functions set a.m_ptr to nullptr. This may seem extraneous -- after all, if a is a temporary r-value, why bother doing “cleanup” if parameter a is going to be destroyed anyway?

The answer is simple: When a goes out of scope, the destructor for a will be called, and a.m_ptr will be deleted. If at that point, a.m_ptr is still pointing to the same object as m_ptr , then m_ptr will be left as a dangling pointer. When the object containing m_ptr eventually gets used (or destroyed), we’ll get undefined behavior.

When implementing move semantics, it is important to ensure the moved-from object is left in a valid state, so that it will destruct properly (without creating undefined behavior).

Automatic l-values returned by value may be moved instead of copied

In the generateResource() function of the Auto_ptr4 example above, when variable res is returned by value, it is moved instead of copied, even though res is an l-value. The C++ specification has a special rule that says automatic objects returned from a function by value can be moved even if they are l-values. This makes sense, since res was going to be destroyed at the end of the function anyway! We might as well steal its resources instead of making an expensive and unnecessary copy.

Although the compiler can move l-value return values, in some cases it may be able to do even better by simply eliding the copy altogether (which avoids the need to make a copy or do a move at all). In such a case, neither the copy constructor nor move constructor would be called.

Disabling copying

In the Auto_ptr4 class above, we left in the copy constructor and assignment operator for comparison purposes. But in move-enabled classes, it is sometimes desirable to delete the copy constructor and copy assignment functions to ensure copies aren’t made. In the case of our Auto_ptr class, we don’t want to copy our templated object T -- both because it’s expensive, and whatever class T is may not even support copying!

Here’s a version of Auto_ptr that supports move semantics but not copy semantics:

If you were to try to pass an Auto_ptr5 l-value to a function by value, the compiler would complain that the copy constructor required to initialize the function parameter has been deleted. This is good, because we should probably be passing Auto_ptr5 by const l-value reference anyway!

Auto_ptr5 is (finally) a good smart pointer class. And, in fact the standard library contains a class very much like this one (that you should use instead), named std::unique_ptr. We’ll talk more about std::unique_ptr later in this chapter.

Another example

Let’s take a look at another class that uses dynamic memory: a simple dynamic templated array. This class contains a deep-copying copy constructor and copy assignment operator.

Now let’s use this class in a program. To show you how this class performs when we allocate a million integers on the heap, we’re going to leverage the Timer class we developed in lesson 18.4 -- Timing your code . We’ll use the Timer class to time how fast our code runs, and show you the performance difference between copying and moving.

On one of the author’s machines, in release mode, this program executed in 0.00825559 seconds.

Now let’s run the same program again, replacing the copy constructor and copy assignment with a move constructor and move assignment.

On the same machine, this program executed in 0.0056 seconds.

Comparing the runtime of the two programs, (0.00825559 - 0.0056) / 0.00825559 * 100 = 32.1% faster!

Do not implement move semantics using std::swap

Since the goal of move semantics is to move a resource from a source object to a destination object, you might think about implementing the move constructor and move assignment operator using std::swap() . However, this is a bad idea, as std::swap() calls both the move constructor and move assignment on move-capable objects, which would result in an infinite recursion. You can see this happen in the following example:

This prints:

And so on… until the stack overflows.

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 move assignment. Here’s an example of how that can be done:

This works as expected, and prints:

Deleting the move constructor and move assignment

You can delete the move constructor and move assignment using the = delete syntax in the exact same way you can delete the copy constructor and copy assignment.

If you delete the copy constructor, the compiler will not generate an implicit move constructor (making your objects neither copyable nor movable). Therefore, when deleting the copy constructor, it is useful to be explicit about what behavior you want from your move constructors. Either explicitly delete them (making it clear this is the desired behavior), or default them (making the class move-only).

The rule of five says that if the copy constructor, copy assignment, move constructor, move assignment, or destructor are defined or deleted, then each of those functions should be defined or deleted.

While deleting only the move constructor and move assignment may seem like a good idea if you want a copyable but not movable object, this has the unfortunate consequence of making the class not returnable by value in cases where mandatory copy elision does not apply. This happens because a deleted move constructor is still declared, and thus is eligible for overload resolution. And return by value will favor a deleted move constructor over a non-deleted copy constructor. This is illustrated by the following program:

guest

cppreference.com

Move constructors.

A move constructor of class T is a non-template constructor whose first parameter is T && , const T && , volatile T && , or const volatile T && , and either there are no other parameters, or the rest of the parameters all have default values.

[ edit ] Syntax

Where class_name must name the current class (or current instantiation of a class template), or, when declared at namespace scope or in a friend declaration, it must be a qualified class name.

[ edit ] Explanation

  • Typical declaration of a move constructor.
  • Forcing a move constructor to be generated by the compiler.
  • Avoiding implicit move constructor.

The move constructor is typically called when an object is initialized (by direct-initialization or copy-initialization ) from rvalue (xvalue or prvalue) (until C++17) xvalue (since C++17) of the same type, including

  • initialization: T a = std :: move ( b ) ; or T a ( std :: move ( b ) ) ; , where b is of type T ;
  • function argument passing: f ( std :: move ( a ) ) ; , where a is of type T and f is void f ( T t ) ;
  • function return: return a ; inside a function such as T f ( ) , where a is of type T which has a move constructor.

When the initializer is a prvalue, the move constructor call is often optimized out (until C++17) never made (since C++17) , see copy elision .

Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.) rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, moving from a std::string or from a std::vector may result in the argument being left empty. However, this behavior should not be relied upon. For some types, such as std::unique_ptr , the moved-from state is fully specified.

[ edit ] Implicitly-declared move constructor

If no user-defined move constructors are provided for a class type ( struct , class , or union ), and all of the following is true:

  • there are no user-declared copy constructors ;
  • there are no user-declared copy assignment operators ;
  • there are no user-declared move assignment operators ;
  • there are no user-declared destructors ;

then the compiler will declare a move constructor as a non- explicit inline public member of its class with the signature T::T(T&&) .

A class can have multiple move constructors, e.g. both T :: T ( const T && ) and T :: T ( T && ) . If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword default .

The implicitly-declared (or defaulted on its first declaration) move constructor has an exception specification as described in dynamic exception specification (until C++17) exception specification (since C++17)

[ edit ] Deleted implicitly-declared move constructor

The implicitly-declared or defaulted move constructor for class T is defined as deleted if any of the following is true:

  • T has non-static data members that cannot be moved (have deleted, inaccessible, or ambiguous move constructors);
  • T has direct or virtual base class that cannot be moved (has deleted, inaccessible, or ambiguous move constructors);
  • T has direct or virtual base class with a deleted or inaccessible destructor;
  • T is a union-like class and has a variant member with non-trivial move constructor;

[ edit ] Trivial move constructor

The move constructor for class T is trivial if all of the following is true:

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the move constructor selected for every direct base of T is trivial;
  • the move constructor selected for every non-static class type (or array of class type) member of T is trivial;

A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially movable.

[ edit ] Implicitly-defined move constructor

If the implicitly-declared move constructor is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used . For union types, the implicitly-defined move constructor copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument. If this satisfies the requirements of a constexpr constructor , the generated move constructor is constexpr .

[ edit ] Notes

To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. For example, std::vector relies on std::move_if_noexcept to choose between move and copy when the elements need to be relocated.

If both copy and move constructors are provided and no other constructors are viable, overload resolution selects the move constructor if the argument is an rvalue of the same type (an xvalue such as the result of std::move or a prvalue such as a nameless temporary (until C++17) ), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.

A constructor is called a 'move constructor' when it takes an rvalue reference as a parameter. It is not obligated to move anything, the class is not required to have a resource to be moved and a 'move constructor' may not be able to move a resource as in the allowable (but maybe not sensible) case where the parameter is a const rvalue reference (const T&&).

[ edit ] Example

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 18 February 2019, at 03:43.
  • This page has been accessed 606,979 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers
  • Analysis of Algorithms
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms

std::move in Utility in C++ | Move Semantics, Move Constructors and Move Assignment Operators

  • How to Implement Move Assignment Operator in C++?
  • Default Assignment Operator and References in C++
  • Move Assignment Operator in C++ 11
  • How to Create Custom Assignment Operator in C++?
  • std::is_nothrow_move_constructible in C++ with Example
  • std::is_trivially_move_constructible in C++ with Examples
  • std::is_move_constructible in C++ with Examples
  • When should we write our own assignment operator in C++?
  • std::is_trivially_move_assignable in C++ with Examples
  • C++ Assignment Operator Overloading
  • Assignment Operators In C++
  • When Should We Write Our Own Copy Constructor in C++?
  • std::is_copy_assignable in C++ with Examples
  • Move Constructors in C++ with Examples
  • std::is_nothrow_move_assignable in C++
  • std::is_move_assignable C++ with Examples
  • Overloads of the Different References in C++
  • Conversion Operators in C++
  • unordered_set operator= in C++ STL
  • Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
  • Top 50 Array Coding Problems for Interviews
  • Introduction to Recursion - Data Structure and Algorithm Tutorials
  • Difference between BFS and DFS
  • Must Do Coding Questions for Product Based Companies
  • A* Search Algorithm
  • Top 10 Algorithms in Interview Questions
  • Sliding Window Technique
  • How to write a Pseudo Code?
  • Asymptotic Notation and Analysis (Based on input size) in Complexity Analysis of Algorithms

Prerequisites:

  • lvalue reference
  • rvalue reference
  • Copy Semantics (Copy Constructor)

References:

In C++ there are two types of references-

  • An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.
  • Simply, a variable or object that has a name and memory address.
  • It uses one ampersand (&).
  • An rvalue is an expression that will appear only on the right-hand side of an assignment.
  • A variable or object has only a memory address (temporary objects).
  • It uses two ampersands (&&).

Move Constructor And Semantics:

The move constructor was introduced in C++11 . The need or purpose of a move constructor is to steal or move as many resources as it can from the source (original) object , as fast as possible, because the source does not need to have a meaningful value anymore, and/or because it is going to be destroyed in a moment anyway. So that one can avoid unnecessarily creating copies of an object and make efficient use of the resources

While one can steal the resources, but one must leave the source (original) object in a valid state where it can be correctly destroyed.

Move constructors typically “steal” the resource of the source (original) object rather than making several copies of them, and leaves the source object in a “valid but unspecified state”.

The copy constructor uses the lvalue references which are marked with one ampersand (&) while the move constructor uses the rvalue references are marked with two ampersands (&&).

std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move() is defined in the <utility> header .
template< class T >  typename std::remove_reference<T>::type&& move(T&& t) noexcept;                 (since C++11)(until C++14) template< class T >  constexpr std::remove_reference_t<T>&& move(T&& t) noexcept                       (since C++14)

Example: Below is the C++ program to show what happens without using move semantics i.e. before C++11.

Explanation:

Assuming the program is compiled and executed using a compiler that doesn’t support move semantics. In the main() function,  

1. std::vector<std::string> vecString;- An empty vector is created with no elements in it.  2. vecString = createAndInsert();- The createAndInsert() function is called. 3. In createAndInsert() function-

  • std::vector<std::string> vec;- Another new empty vector named as vec is created.
  • vec.reserve(3);- Reserving the size of 3 elements.
  • std::string str(“Hello”);- A string named as str initialized with a “Hello”.
  • vec.push_back( str );- A string is passed by value into the vector vec. Therefore a (deep) copy of str will be created and inserted into the vec by calling a copy constructor of the String class.
  • A temporary object will be created (str + str) with its own separate memory.
  • This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created.
  • As of now, the temporary object is no longer needed hence it will be destroyed.

Note: Here, we unnecessarily allocate & deallocate the memory of the temporary string object. which can be optimized (improved) further just by moving the data from the source object. 

  • vec.push_back( str );- The same process as of Line no. 5 will be carried out. Remember at this point the str string object will be last used.
  • Firstly, the string object str will be destroyed because the scope is left where it is declared.
  • Secondly, a local vector of string i.e vec is returned. As the return type of the function is not by a reference. Hence, a deep copy of the whole vector will be created by allocating at a separate memory location and then destroys the local vec object because the scope is left where it is declared.
  • Finally, the copy of the vector of strings will be returned to the caller main() function.
  • At the last, after returning to the caller main() function, simply printing the elements of the local vecString vector.

Example: Below is the C++ program to implement the above concept using move semantics i.e. since C++11 and later. 

Here, in order to use the move semantics. The compiler must support the C++11 standards or above. The story of execution for the main() function and createAndInsert() function remains the same till the line vec.push_back( str );

A question may arise why the temporary object is not moved to vector vec using std::move(). The reason behind it is the push_back() method of the vector. Since C++11 the push_back() method has been provided with its new overloaded version.

Syntax:  

constexpr void push_back(const T& value);                                        (since C++20) void push_back(T&& value);                                                              (since C++11) (until C++20) void push_back(const T& value);                                                        (until C++20) constexpr void push_back(T&& value);                                              (since C++20)
  • A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd  or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required.
  • After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data.
  • Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics.
  • vec.push_back(std::move(str));- Here the compiler is explicitly hinted that “object is no longer needed” named as str ( lvalue reference ) with the help of std::move() function by converting the lvalue reference into rvalue reference and the resource of the str will be moved to the vector. Then the state of str becomes a “valid but unspecified state”. This doesn’t matter to us because for the last time we are going to use and soon be destroyed in a moment anyway.
  • Lastly, return the local vector of string called vec to its caller.
  • In the end, returned to the caller main() function, and simply printing the elements of the local vecString vector.

A question may arise while returning the vec object to its caller. As it is not required anymore and also a whole temporary object of a vector is going to be created and also local vector vec will be destroyed, then why std::move() is not used to steal the value and return it.  Its answer is simple and obvious, there is optimization at the compiler level known as (Named) Return Value Object, more popularly known as RVO . 

Some Fallback Of Move Semantics:  

  • It doesn’t make any sense to steal or move the resources of a const object.
  • See constObjectCallFunc() function in the below program
  • See baz() function in the below program
  • See bar() function in the below program

Note: The foo() function have all necessary types of arguments.

Below is the C++ program to implement all the above concepts- 

Summary:  

  • Move semantics allows us to optimize the copying of objects, where we do not need the worth. It is often used implicitly (for unnamed temporary objects or local return values) or explicitly with std::move().
  • std::move() means “no longer need this value” .
  • An object marked with std::move() is never partially destroyed. i.e. The destructor will be called to destroy the object properly.

Please Login to comment...

Similar reads.

  • Blogathon-2021
  • Constructors
  • C++ Programs
  • Competitive Programming

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

Search

Move constructors

A move constructor of class T is a non-template constructor whose first parameter is T && , const T && , volatile T && , or const volatile T && , and either there are no other parameters, or the rest of the parameters all have default values. A type with a public move constructor is MoveConstructible .

[ edit ] Syntax

[ edit ] explanation.

  • Typical declaration of a move constructor
  • Forcing a move constructor to be generated by the compiler
  • Avoiding implicit move constructor

The move constructor is called whenever an object is initialized from xvalue of the same type, which includes

  • initialization, T a = std:: move ( b ) ; or T a ( std:: move ( b ) ) ; , where b is of type T
  • function argument passing: f ( std:: move ( a ) ) ; , where a is of type T and f is void f ( T t )
  • function return: return a ; inside a function such as T f ( ) , where a is of type T which has a move constructor.

Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, moving from a std:: string or from a std:: vector turns the argument empty.

[ edit ] Implicitly-declared move constructor

If no user-defined move constructors are provided for a class type ( struct , class , or union ), and all of the following is true:

  • there are no user-declared copy constructors
  • there are no user-declared copy assignment operators
  • there are no user-declared move assignment operators
  • there are no user-declared destructurs
  • the implicitly-declared move constructor would not be defined as deleted

then the compiler will declare a move constructor as an inline public member of its class with the signature T::T(T&&)

A class can have multiple move constructors, e.g. both T :: T ( const T && ) and T :: T ( T && ) . If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword default .

[ edit ] Deleted implicitly-declared move constructor

The implicitly-declared or defaulted move constructor for class T is defined as deleted in any of the following is true:

  • T has non-static data members that cannot be moved (have deleted, inaccessible, or ambiguous move constructors)
  • T has direct or virtual base class that cannot be moved (has deleted, inaccessible, or ambiguous move constructors)
  • T has direct or virtual base class with a deleted or inaccessible destructor
  • T has a user-defined move constructor or move assignment operator
  • T is a union and has a variant member with non-trivial copy constructor
  • T has a non-static data member or a direct or virtual base without a move constructor that is not trivially copyable.

[ edit ] Trivial move constructor

The implicitly-declared move constructor for class T is trivial if all of the following is true:

  • T has no virtual member functions
  • T has no virtual base classes
  • The move constructor selected for every direct base of T is trivial
  • The move constructor selected for every non-static class type (or array of class type) memeber of T is trivial

A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by std:: memmove . All data types compatible with the C language (POD types) are trivially movable.

[ edit ] Implicitly-defined move constructor

If the implicitly-declared move constructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. For union types, the implicitly-defined move constructor copies the object representation (as by std:: memmove ). For non-union class types ( class and struct ), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument.

[ edit ] Notes

To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. In fact, standard containers typically rely on std:: move_if_noexcept to choose between move and copy when container elements need to be relocated.

If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std:: move ), and selects the copy constructor if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.

[ edit ] Example

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • This page was last modified on 15 June 2012, at 14:13.
  • This page has been accessed 46 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Move assignment operator

A move assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T && , const T && , volatile T && , or const volatile T && . A type with a public move assignment operator is MoveAssignable .

[ edit ] Syntax

[ edit ] explanation.

  • Typical declaration of a move assignment operator
  • Forcing a move assignment operator to be generated by the compiler
  • Avoiding implicit move assignment

The move assignment operator is called whenever it is selected by overload resolution , e.g. when an object appears on the left side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std:: string or from a std:: vector leaves the right-hand side argument empty.

[ edit ] Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type ( struct , class , or union ), and all of the following is true:

  • there are no user-declared copy constructors
  • there are no user-declared move constructors
  • there are no user-declared copy assignment operators
  • there are no user-declared destructors
  • the implicitly-declared move assignment operator would not be defined as deleted

then the compiler will declare a move assignment operator as an inline public member of its class with the signature T& T::operator= T(T&&)

A class can have multiple move assignment operators, e.g. both T & T :: operator = ( const T && ) and T & T :: operator = ( T && ) . If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword default .

Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Deleted implicitly-declared move assignment operator

The implicitly-declared or defaulted move assignment operator for class T is defined as deleted in any of the following is true:

  • T has a non-static data member that is const
  • T has a non-static data member of a reference type.
  • T has a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)
  • T has direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator)
  • T has a non-static data member or a direct or virtual base without a move assignment operator that is not trivially copyable.
  • T has a direct or indirect virtual base class

[ edit ] Trivial move assignment operator

The implicitly-declared move assignment operator for class T is trivial if all of the following is true:

  • T has no virtual member functions
  • T has no virtual base classes
  • The move assignment operator selected for every direct base of T is trivial
  • The move assignment operator selected for every non-static class type (or array of class type) memeber of T is trivial

A trivial move assignment operator performs the same action as the trivial copy assignment operator, that is, makes a copy of the object representation as if by std:: memmove . All data types compatible with the C language (POD types) are trivially move-assignable.

[ edit ] Implicitly-defined move assignment operator

If the implicitly-declared move assignment operator is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. For union types, the implicitly-defined move assignment operator copies the object representation (as by std:: memmove ). For non-union class types ( class and struct ), the move assignment operator performs full member-wise move assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and move assignment operator for class types.

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std:: move ), and selects the copy assignment if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

The copy-and-swap assignment operator

T & T :: operator = ( T arg ) {     swap ( arg ) ;     return * this ; }

performs an equivalent of move assignment for rvalue arguments at the cost of one additional call to the move constructor of T, which is often acceptable.

[ edit ] Example

Move assignment operator

A move assignment operator of class T is a non-template non-static member function with the name operator = that takes exactly one parameter of type T && , const T && , volatile T && , or const volatile T && .

Explanation

  • Typical declaration of a move assignment operator.
  • Forcing a move assignment operator to be generated by the compiler.
  • Avoiding implicit move assignment.

The move assignment operator is called whenever it is selected by overload resolution , e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std::string or from a std::vector may result in the argument being left empty. This is not, however, a guarantee. A move assignment is less, not more restrictively defined than ordinary assignment; where ordinary assignment must leave two copies of data at completion, move assignment is required to leave only one.

Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type ( struct , class , or union ), and all of the following is true:

  • there are no user-declared copy constructors;
  • there are no user-declared move constructors;
  • there are no user-declared copy assignment operators;
  • there are no user-declared destructors;

then the compiler will declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&) .

A class can have multiple move assignment operators, e.g. both T & T :: operator = ( const T && ) and T & T :: operator = ( T && ) . If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword default .

The implicitly-declared (or defaulted on its first declaration) move assignment operator has an exception specification as described in dynamic exception specification (until C++17) exception specification (since C++17)

Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

Deleted implicitly-declared move assignment operator

The implicitly-declared or defaulted move assignment operator for class T is defined as deleted if any of the following is true:

  • T has a non-static data member that is const ;
  • T has a non-static data member of a reference type;
  • T has a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator);
  • T has direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous move assignment operator);

Trivial move assignment operator

The move assignment operator for class T is trivial if all of the following is true:

  • It is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the move assignment operator selected for every direct base of T is trivial;
  • the move assignment operator selected for every non-static class type (or array of class type) member of T is trivial;

A trivial move assignment operator performs the same action as the trivial copy assignment operator, that is, makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially move-assignable.

Implicitly-defined move assignment operator

If the implicitly-declared move assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used .

For union types, the implicitly-defined move assignment operator copies the object representation (as by std::memmove ).

For non-union class types ( class and struct ), the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually).

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator (same applies to copy assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined move-assignment operator.

A blog about C++ programming

Move Semantics: The Basics

Move Semantics

Move semantics was a new addition to C++ that arrived with C++ 11. Newer language standards have continued to expand and improve it. The feature is quite simple, but often misunderstood. I’m often reminded of that when I’m interviewing programmers.

Who will Find this Article Useful?

In this article I will cover all the basics of move semantics. This information will be useful for people that have never used move semantics but for people that are somehow familiar with the topic and use cases but don’t necessary use move semantics very often. The article will also be useful for people that want to dig deeper into the feature. And it will be useful for people that want to refresh their memory.

To benefit from this article to the fullest, you will need a good understanding of how copy constructors and assignment operators work, and you need to have a basic understanding of types and type casting.

1 – The case for Move Semantics

Before we look at the definition of move semantics, let us look at an example that will set up the premise of why move semantics exist.

1.1 – Setting the example

Let us assume that we are going to implement a struct that represents a memory block on the heap. The only thing this struct is responsible for is allocating the memory on construction and deallocating it on destruction. We can imagine that this struct is used by a complex memory allocation system. Let’s say that system is managing many instances of our struct, in other words, it is managing many memory buffers.

Here is the declaration of our struct:

We need to keep the example simple. And variables that could be needed for a robust solution, like used or free bytes and masks of all sorts, are out of the scope of this example.

1.2 – Using the Memory Buffer

Now let us also imagine that there is a free utility function that creates an array of buffers and returns the array. We can assume that this function is used by the complex memory allocation system in order to pre-allocate memory pools of different sizes.

Before C++ 11, no one would write this function in this way. Output parameters as pointer or reference will be used instead. This will make the function more complicated to implement, maintain and use. To explain why this was the case, let us have a look of how the “CreateMemoryPool” function is used. Let us assume that a bunch of pools of various sizes are created by the memory system in an “InitializePools” member function.

We will assume that we are not using any C++ 11 or newer additions to the language. We will also assume that for whatever reason the compiler will decide not to use Copy Elision to omit the copy of the return value of the “CreateMemoryPool(…)” function.

With all of these assumptions in play, calling the “CreateMemoryPool(…)” function will create a temporary return variable that will be used to assign to the member variables via the copy assignment operator of the std::vector. In other words, we are going to do a deep copy. This is very suboptimal way to write such code.

1.3 – The problem: deep copies can be very expensive

The problem with this scenario is that the local pool variable in the “CreateMemoryPool(…)” function, that stored the result of the function, will be copied into the m_PagePool and then destroyed. We are wasting a lot of cycles that way by executing extra instructions. We are also wasting cycles by allocating and deallocating memory (which is quite slow, generally speaking).

Before C++ 11, we would often reach for one of the following to minimize the allocations/deallocations caused by local and temporary variables:

  • Pass a pointer or a reference to the m_PagePool as input to the “CreateMemoryPool(…)” and let the function directly push back into the m_PagePool. In this way “CreateMemoryPool(…)” can return void, and the function is going to work directly on the variable that will store the final result of the function. And in this way we avoid copies. The first drawback is the extra parameter that is passed to the function, adding complexity. For example, doing this creates ambiguity when it comes to responsibility for the input state of that vector. Is it the callers responsibility to ensure that the vector is empty when invoking the function or will the function itself clear the vector? The second is the fact that passing a non-constant pointer or reference of the internal variable m_PagePool makes our code less safe because anyone can write code that does something bad to m_PagePool and the caller of “CreateMemoryPool(…)” loses all guarantees.
  • We can change the result of the function to return a vector of pointers to memory buffers, like so: vector<MemoryBuffer*>. This way we only copy the pointers when the “CreateMemoryPool(…)” function returns and there is no deep copying going on and no extra allocations/deallocations. The drawback to this is now the owner of the m_PagePool needs to worry about manually deallocating the pointers held by the vector, because the vector won’t do it in it own. Of course, we can use a vector of some of smart pointers to automate that part as well, but that also adds complexity.

1.4 – Move semantics solves the possible performance issue with deep copies

What we really want to do is keep the “CreateMemoryPool(…)” function implementation as it is, simple and safe, and move the result of the function directly into the m_PagePool variable without doing a deep copy, as if we are transferring water from one glass directly into another. Furthermore, we are doing even more copying by using the “push_back” function of the vector class and we want the push_back to also behave as if we are transferring water from one glass directly into another. C++ 11 and move semantics allows us to do exactly that. In the following sections, we are going to explore what move semantics are.

2 – Definition of Move Semantics

Move semantics are typically used to “steal” the resources held by another variable of the same type (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.) and leave the source variable in some valid state, rather than making a deep copy of them.

The two most common use cases for move semantics are :

  • Performance: converting an expensive deep copy operation into a cheap move, like moving the data from a source string into a target string without having to allocate/deallocate.
  • Ownership semantics: Implementing user defined data types for which copying is not allowed but moving is, like the std::unique_ptr.

3 – Lvalues, Rvalues and Xvalues

To understand how move semantics work under the hood, we need to define a few other terms. Let’s start by looking at a pseudo-code that represents an assignment statement:

The left side of the statement is what historically is called Lvalue. And the right side of the statement is what historically is called Rvalue. Of course, because of the general nature of C++ things are often more complicated. Rvalues can appear on the left side, and Lvalues on the right side. Why that is the case is not relevant for this article.

3.1 – Easy way to differentiate between Lvalues and Rvalues

You might think that the fact that Lvalues and Rvalues can appear on either side is very confusing. Fortunately, there is a very simple rule we can use to remove all this confusion. A rule that will allow us to easily classify Lvalues and Rvalues in C++.

If a variable has an identifier that you have chosen yourself, then it is an Lvalue. And if a variable does not have a name that you have deliberately selected, then it is an Rvalue. To demonstrate this rule, let’s look at the following code snippets:

Here is another example:

3.2 – Double ampersands(&&) and the new operators

Prior to C++ 11, Rvalues and Lvalues were indistinguishable. The following example code would trigger the copy constructor and the copy assignment operator of the std::vector.

This is the Copy Constructor and the Copy Assignment Operator that would have been used in both cases:

To solve this problem, C++ 11 introduced Rvalue references, denoted by a double ampersands (&&). With this addition, we can now have two different copy constructors and assignment operators. One for Lvalues and one for Rvalues.

The following code snippet shows the declaration of the copy and the move constructors:

The following code snippet shows the declaration of the copy and the move assignment operators:

We can now revisit the example from above. And we can examine how in the cases where we have an Rvalue on the right hand side, the new move constructor and move assignment operators will be called instead of the copy constructor and copy assignment.

4 – Declaring Move Constructor and Move Assignment Operator

Now we know that C++ 11 introduced Rvalue references, denoted by a double ampersands (&&). And we know that we can declare a move constructor and a move assignment operator using the Rvalue type. Let’s declare them for our MemoryBuffer struct:

5 – Defining Move Constructor and Move Assignment Operator

We now know how to declare the move constructor and move assignment operator. It is now time to define them and actually implement the useful move semantics.

What we are doing in the move constructor and the move assignment is identical, except we also need to take care of self assignment in the move assignment operator. Let’s examine what we are doing in the move constructor:

  • In the initializer list, we are copying the source m_Buffer pointer into our own internal m_Buffer pointer. This is a simple pointer copy and not a deep copy. At this point both the source and the internal m_Buffer pointers point to the same memory address.
  • Then, also in the initializer list, we are copying the variable holding the size of the source buffer into the internal m_SizeInBytes variable.
  • Then, in the move constructor body, we set the source buffer pointer to nullptr. Effectively leaving the source pointer in a valid state, but also at this point completing the process of stealing the resource. After this the internal m_Buffer pointer points to where the source m_Buffer pointer used to point.
  • Finally, we reset the m_SizeInBytes of the source to 0, effectively leaving the source MemoryBuffer in a valid state.

For completeness, here is the the entire MemoryBuffer struct:

6 – Move Semantics in Action

With the new knowledge we acquired about Lvalues and Rvalues, as well as with the implementation of the move constructor and move assignment operator, we can now revisit the example we started with and see move semantics in action.

First, let us make a small change in the “CreateMemoryPool(…)” function.

To take advantage of the new move semantics and variadic templates, in C++ 11 a new version of the vector::push_back was added to the standard library. I recommend that you check the documentation, but in a nutshell, emplace_back will construct the new MemoryBuffer right in the memory location where it will be stored by the vector and in this way reducing the need to deep copy.

And finally, let us look at the “InitializePools” member function. Notice that the code is unchanged, but the compiler will call the move assignment operator and avoid deep copy and the extra allocations/deallocations, that are quite slow.

7 – Automatic vs. Manual Move

Looking at the “MemoryAllocationSystem::Initialize()” function, we can easily conclude that if move semantics were available to the compiler and if the types in question (std::vector and MemorBuffer in this case) supports move semantics, the compiler will detect the opportunity to move instead of copy. The reason for this is that the compiler will be able to see that the local variable created and returned by the “CreateMemoryPool(…)” is in fact an Rvalue.

The compiler is unable to detect every move opportunity. We can create a situation where we, as programmers, might have the intent to move the content of one array into another array (for whatever reasons) but the compiler will not be able to automatically detect our intent to move and will fallback to a deep copy. This of course happens when we have the intention to move an Lvalue into another Lvalue. Here is an example:

By default, the compiler will correctly assume that we ask for a deep copy. And if we really want to move, then we need to help the compiler a bit and turn the right hand Lvalues into Rvalue. To explicitly tell the compiler what our intent is, C++ 11 introduced a helper function: std::move . To utilize this new helper function, we can change our example to the following:

All std::move does is a cast. It casts the “ pool1 ” variable from an Lvalue reference (&) to an Rvalue reference (&&). Doing so tells the compiler which assignment operator it should call, because the variable type changes. And of course this is all based on standard function overloading rules. In its core, the assignment operator is a function, which is overloaded for two different input types (Lvalue reference and Rvalue reference).

8 – Xvalue

The following is a bit of an extra context and not absolutely necessary for this article, but I would rather mention it. The “ pool1 ” variable, in the example above, is technically an Xvalue after the std::move is executed. For all intent and purposes, you can treat it as an Lvalue, but the language implementers need a technical term for it. It means expiring value and it denotes an Lvalue object that can be reused after a move from it was executed. There are exactly three things that can be done to an Xvalue:

  • Copy assign to the Xvalue, turning it into an Lvalue.
  • Move assign to the Xvalue, turning it into an Lvalue.
  • Call the destructor when the Xvalue goes out of scope.

9 – Special Operators’ Rules

We all know that sometimes the compiler will generate constructors and other special operators on its own. The good news is that there are rules for when the compiler will do that. And now with the new move constructor and move assignment operator, these rules have been updated. For completeness, it is worth mentioning the most important rules here.

Rule 1 : Default move operations are generated only if no copy operations or destructor is user defined. This is because C++ assumes that if you need a destructor or you manually implemented copy operations, or both, then you are dealing with some sort of resource that needs special treatment. And because it is a resource, you need to implement the move operations yourself because you, as the expert, know best how this resources should behave.

Rule 2 : Default copy operations are generated only if there is no user defined move operations. The reasons here are are the same as in Rule 1. Note that =default and =delete count as user defined.

Rule 3 : You don’t need to implement move semantics or even copy semantics manually if all of the internal member variables are of types that are movable or copyable. For example, if we were to change the “char* m_Buffer” in our MemoryBuffer class to “unique_ptr<char> m_Buffer”, then we do not need to implement the move semantics ourselves, because the unique_ptr<T> class already supports move semantics.

10 – Parameters Convention

Move semantics is an optimization that is only applicable to some use cases. In general prefer simple and conventional ways of passing information. The following table illustrates an accepted convention for passing parameters and what types you should use. When in doubt, always check it.

Move Semantics and Parameters Convention

11 – Forwarding a Reference

For completeness, I need to cover one last topic. One more function was introduced together with std::move in C++ 11. And it was std::forward.

std::forward is pretty simple as it has only one use case. Its purpose is to preserve the value type, regardless if it is Lvalue or Rvalue, and pass it on. This is also called perfect forwarding. Typically a function accepting an Rvalue will attempt to move it and invalidate it, and when this is not the case, we can use std::forwad to pass on the Rvalue down the call-stack. The following example illustrates the use case.

For completeness, it is worth mentioning that In the code example above the input “T&& inArg” is called Forwarding reference . Forwarding references are a special kind of references that preserve the value category of a function argument. In this case calling “std::forward<T>(inArg)” will preserve the input argument and will forward it as Lvalue it if the input is an Lvalue, or it will forward it as Rvalue if the input is an Rvalue.

12 – Conclusion

In general, the concept of move semantics is quite simple and as programmers we should learn how and when to use it. The concept is built based on two fundamental C++ concepts: types and function/operator overloading. The following is a list of takeaway:

  • Pre-C++ 11, value semantics sometimes lead to unnecessary and possibly expensive deep copy operations.
  • C++ 11 introduces Rvalue references to distinguish from Lvalue references. And it also introduces std::move to cast from Lvalue to Rvalue.
  • From C++ 11 on, temporary variables are treated as Rvalues.
  • Moving POD or structs composed of PODs will not give you any benefits. To get benefits from move semantics you need some kind of resource (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.).

13 – Source Code

The source code containing the MemoryBuffer example is here (under MoveSemantics ). You do not need a Github account to download it. When you open the repository, click on the Code button and choose Donwload ZIP .

14 – Credit

Special thanks to my colleagues for spending their personal time proofreading, challenge this article and helping me to make it better. It is a pleasure working with every one of you!

  • Anton Andersson : Senior Gameplay Programmer at IO Interactive.
  • Nils Iver Holtar : Lead AI Programmer at IO Interactive.

Please consider sharing this post if you find the information useful.

' src=

Post navigation

Previous post.

Firefox is no longer supported on Windows 8.1 and below.

Please download Firefox ESR (Extended Support Release) to use Firefox.

Download Firefox ESR 64-bit

Download Firefox ESR 32-bit

Firefox is no longer supported on macOS 10.14 and below.

Mozilla Foundation Security Advisory 2024-18

Security vulnerabilities fixed in firefox 125.

  • Firefox 125

# CVE-2024-3852: GetBoundName in the JIT returned the wrong object

Description.

GetBoundName could return the wrong version of an object when JIT optimizations were applied.

  • Bug 1883542

# CVE-2024-3853: Use-after-free if garbage collection runs during realm initialization

A use-after-free could result if a JavaScript realm was in the process of being initialized when a garbage collection started.

  • Bug 1884427

# CVE-2024-3854: Out-of-bounds-read after mis-optimized switch statement

In some code patterns the JIT incorrectly optimized switch statements and generated code with out-of-bounds-reads.

  • Bug 1884552

# CVE-2024-3855: Incorrect JIT optimization of MSubstr leads to out-of-bounds reads

In certain cases the JIT incorrectly optimized MSubstr operations, which led to out-of-bounds reads.

  • Bug 1885828

# CVE-2024-3856: Use-after-free in WASM garbage collection

A use-after-free could occur during WASM execution if garbage collection ran during the creation of an array.

  • Bug 1885829

# CVE-2024-3857: Incorrect JITting of arguments led to use-after-free during garbage collection

The JIT created incorrect code for arguments in certain cases. This led to potential use-after-free crashes during garbage collection.

  • Bug 1886683

# CVE-2024-3858: Corrupt pointer dereference in js::CheckTracedThing<js::Shape>

It was possible to mutate a JavaScript object so that the JIT could crash while tracing it.

  • Bug 1888892

# CVE-2024-3859: Integer-overflow led to out-of-bounds-read in the OpenType sanitizer

On 32-bit versions there were integer-overflows that led to an out-of-bounds-read that potentially could be triggered by a malformed OpenType font.

  • Bug 1874489

# CVE-2024-3860: Crash when tracing empty shape lists

An out-of-memory condition during object initialization could result in an empty shape list. If the JIT subsequently traced the object it would crash.

  • Bug 1881417

# CVE-2024-3861: Potential use-after-free due to AlignedBuffer self-move

If an AlignedBuffer were assigned to itself, the subsequent self-move could result in an incorrect reference count and later use-after-free.

  • Bug 1883158

# CVE-2024-3862: Potential use of uninitialized memory in MarkStack assignment operator on self-assignment

The MarkStack assignment operator, part of the JavaScript engine, could access uninitialized memory if it were used in a self-assignment.

  • Bug 1884457

# CVE-2024-3863: Download Protections were bypassed by .xrm-ms files on Windows

The executable file warning was not presented when downloading .xrm-ms files. Note: This issue only affected Windows operating systems. Other operating systems are unaffected.

  • Bug 1885855

# CVE-2024-3302: Denial of Service using HTTP/2 CONTINUATION frames

There was no limit to the number of HTTP/2 CONTINUATION frames that would be processed. A server could abuse this to create an Out of Memory condition in the browser.

  • Bug 1881183
  • VU#421644 - HTTP/2 CONTINUATION frames can be utilized for DoS attacks

# CVE-2024-3864: Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

Memory safety bug present in Firefox 124, Firefox ESR 115.9, and Thunderbird 115.9. This bug showed evidence of memory corruption and we presume that with enough effort this could have been exploited to run arbitrary code.

  • Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

# CVE-2024-3865: Memory safety bugs fixed in Firefox 125

Memory safety bugs present in Firefox 124. Some of these bugs showed evidence of memory corruption and we presume that with enough effort some of these could have been exploited to run arbitrary code.

  • Memory safety bugs fixed in Firefox 125

IMAGES

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

    move constructor move assignment operator

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

    move constructor move assignment operator

  3. C++ : rvalue references, move constructor & move assignment operator

    move constructor move assignment operator

  4. What is move constructor and why it take r-value?

    move constructor move assignment operator

  5. C++11 Tutorial: Introducing the Move Constructor and the Move

    move constructor move assignment operator

  6. Learn Advanced C++ Programming move assignment operators

    move constructor move assignment operator

VIDEO

  1. 050322 C++ Vector Class Dynamic memory: move constructor and assignment

  2. OOP Concept Week Part 1 || Constructors

  3. #20. Assignment Operators in Java

  4. Move Constructor in C++

  5. Obsolete attribute is ignored in constructor property assignment

  6. Move Move

COMMENTS

  1. 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 ...

  2. 22.3

    C++11 defines two new functions in service of move semantics: a move constructor, and a move assignment operator. Whereas the goal of the copy constructor and copy assignment is to make a copy of one object to another, the goal of the move constructor and move assignment is to move ownership of the resources from one object to another (which is typically much less expensive than making a copy).

  3. Move constructors

    there are no user-declared move assignment operators; there is no user-declared destructor. Then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T:: T (T &&). A class can have multiple move constructors, e.g. both T:: T (const T &&) and T:: T (T &&).

  4. Difference between the move assignment operator and move constructor?

    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 scenario as in the copy case. Foo foo = std::move(bar); // construction, invokes move constructor. foo = std::move(other); // assignment, invokes move assignment operator.

  5. Move assignment operator

    The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.. Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors ...

  6. Move Constructors in C++ with Examples

    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. Syntax of the Move Constructor: : data{ obj.data } // Nulling out the pointer to the temporary data. obj.data = nullptr;

  7. Move Assignment Operator in C++ 11

    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.

  8. C++11 Tutorial: Introducing the Move Constructor and the Move

    Designing a Move Assignment Operator. A move assignment operator has the following signature: C& C::operator= (C&& other);//C++11 move assignment operator. A move assignment operator is similar to a copy constructor except that before pilfering the source object, it releases any resources that its object may own.

  9. Move constructors

    then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).A class can have multiple move constructors, e.g. both T:: T (const T &&) and T:: T (T &&).If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword default.

  10. Move constructors

    move assignment operator (C++11) destructor: Inheritance : base and derived classes: ... A move constructor of class T is a non-template constructor whose first parameter is T &&, const T &&, volatile T &&, or const volatile T &&, and either there are no other parameters, or the rest of the parameters all have default values. Syntax.

  11. std::move in Utility in C++

    The move constructor was introduced in C++11.The need or purpose of a move constructor is to steal or move as many resources as it can from the source (original) object, as fast as possible, because the source does not need to have a meaningful value anymore, and/or because it is going to be destroyed in a moment anyway.So that one can avoid unnecessarily creating copies of an object and make ...

  12. Move assignment operator

    The move assignment operator, like most C++ operators, can be overloaded. Like the copy assignment operator it is a special member function . If the move assignment operator is not explicitly defined, the compiler generates an implicit move assignment operator ( C++11 and newer) provided that copy / move constructors , copy assignment operator ...

  13. Move constructors

    If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std:: move), and selects the copy constructor if the argument is lvalue (named object or a function/operator returning lvalue reference). If ...

  14. Move assignment operator

    Forcing a move assignment operator to be generated by the compiler. Avoiding implicit move assignment. The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

  15. Move assignment operator

    then the compiler will declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&). A class can have multiple move assignment operators, e.g. both T& T::operator=(const T&&) and T& T::operator=(T&&). If some user-defined move assignment operators are present, the user may still force the ...

  16. Move Semantics: The Basics

    And now with the new move constructor and move assignment operator, these rules have been updated. For completeness, it is worth mentioning the most important rules here. Rule 1: Default move operations are generated only if no copy operations or destructor is user defined. This is because C++ assumes that if you need a destructor or you ...

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

    We continue our series on C++11 features you might have forgotten or never learned. Specifically, we will talk about the move constructor and move assignment...

  18. Implementing Move Constructor by Calling 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: // Move constructor. : _data(NULL) , _length(0 ...

  19. Vector with move constructor and move assignment operator

    3. Now you can release the old resources. This is unlikely to go wrong; But even if something goes wrong your object is in a good state. So your Copy assignment should look like this: MyVector& operator=(const MyVector& rhs) {. // Make a copy to temp. std::size_t tSize = rhs.m_Size; int* tInt = new int[tSize];

  20. c++

    I'm new to move semantics, and I've been reading several resources that explain the correct way of defining a move constructor and assignment operator. All introductory material seems to use a class with a pointer member variable as examples. However I don't understand what to do with reference data members and class data members. For example:

  21. Security Vulnerabilities fixed in Firefox 125

    If an AlignedBuffer were assigned to itself, the subsequent self-move could result in an incorrect reference count and later use-after-free. References. Bug 1883158 # CVE-2024-3862: Potential use of uninitialized memory in MarkStack assignment operator on self-assignment Reporter Ronald Crane Impact moderate Description

  22. C++ Rule of 5 copy and move (constructor and assignment) caveat: to

    I am writing a c++11+ standards compliant class, and it is time for me to implement the rule of 5. Destructor Copy Constructor Move Constructor Copy Assignment Operator Move Assignment Operator I...

  23. C++ Move copy constructor and Move Assignment operator

    I have made a simple application with move copy constructor and move copy assignment operator and on each of them I have made a cout statement just to tell me, which are being executed. But during execution, I did not see any statement from the move copy operators but only from default one which the compiler already provides. Here is my code: