cppreference.com
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 content of the argument, possibly mutating the argument.

[ edit ] Syntax
For the formal move assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid move assignment operator syntaxes.
[ edit ] Explanation
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.
[ edit ] Implicitly-declared move assignment operator
If no user-defined move assignment operators are provided for a class type, 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 is no user-declared destructor ,
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) noexcept 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.
[ edit ] 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 or needed for constant evaluation (since C++14) .
For union types, the implicitly-defined move assignment operator copies the object representation (as by std::memmove ).
For non-union class types, 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).
As with copy assignment, 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:
[ edit ] Deleted move assignment operator
The implicitly-declared or defaulted move assignment operator for class T is defined as deleted if any of the following conditions is satisfied:
- T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
- T has a non-static data member of a reference type.
- T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's move assignment operator
- does not result in a usable candidate, or
- in the case of the subobject being a variant member , selects a non-trivial function.
A deleted implicitly-declared move assignment operator is ignored by overload resolution .
[ edit ] 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.
[ edit ] Eligible move assignment operator
Triviality of eligible move assignment operators determines whether the class is a trivially copyable type .
[ edit ] Notes
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.
[ edit ] Example
[ edit ] defect reports.
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
[ edit ] See also
- constructor
- converting constructor
- copy assignment
- copy constructor
- default constructor
- aggregate initialization
- constant initialization
- copy initialization
- default initialization
- direct initialization
- list initialization
- reference initialization
- value initialization
- zero initialization
- move constructor
- 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 17 October 2023, at 00:50.
- This page has been accessed 740,648 times.
- Privacy policy
- About cppreference.com
- Disclaimers

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
Submit and view feedback for
Additional resources
- C++ Data Types
- C++ Operators
- C++ Input/Output
- C++ Control Statements
- C++ Functions
- C++ Strings
- C++ Pointers
- C++ Memory Management
- C++ Exception Handling
- C++ Templates
- C++ Interview Questions

- Explore Our Geeks Community
- C++ 11 - <atomic> Header
- std::move_iterator in C++ 11
- Macros In C++
- C++20 std::basic_syncbuf
- Array Decay In C
- Difference Between Compile Time And Run Time Polymorphism In C++
- Nested Inline Namespaces In C++20
- auto_ptr in C++
- Nested Try Blocks in C++
- C++ Program For Sentinel Linear Search
- Unique_ptr in C++
- Dereference Pointer in C
- Rethrowing an Exception in C++
- std::endian in C++ 20
- Variable Shadowing in C++
- Mutex in C++
- C++ 20 - <semaphore> Header
- std::shared_mutex in C++
- Pass By Reference In 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.
Please Login to comment...
- Geeks Premier League 2023
- Geeks Premier League
Please write us at [email protected] to report any issue with the above content
Improve your Coding Skills with Practice

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.
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
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 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:
Use Move Constructor and Move Assignment Operator - C++ Class
C++ examples for Class:Constructor
Description
Use Move Constructor and Move Assignment Operator
Related Tutorials
- Sign In / Suggest an Article
Current ISO C++ status
Upcoming ISO C++ meetings
Upcoming C++ conferences
Compiler conformance status
C++ (on Sea) Online
February 7-9
ISO C++ committee meeting
March 18-23, Tokyo, Japan
April 17-20, Bristol, UK
C++ Now 2024
May 7-12, Aspen, CO, USA
June 24-29, St. Louis, MO, USA
July 2-5, Folkestone, Kent, UK
assignment operators
Assignment operators, what is “self assignment”.
Self assignment is when someone assigns an object to itself. For example,
Obviously no one ever explicitly does a self assignment like the above, but since more than one pointer or reference can point to the same object (aliasing), it is possible to have self assignment without knowing it:
This is only valid for copy assignment. Self-assignment is not valid for move assignment.
Why should I worry about “self assignment”?
If you don’t worry about self assignment , you’ll expose your users to some very subtle bugs that have very subtle and often disastrous symptoms. For example, the following class will cause a complete disaster in the case of self-assignment:
If someone assigns a Fred object to itself, line #1 deletes both this->p_ and f.p_ since *this and f are the same object. But line #2 uses *f.p_ , which is no longer a valid object. This will likely cause a major disaster.
The bottom line is that you the author of class Fred are responsible to make sure self-assignment on a Fred object is innocuous . Do not assume that users won’t ever do that to your objects. It is your fault if your object crashes when it gets a self-assignment.
Aside: the above Fred::operator= (const Fred&) has a second problem: If an exception is thrown while evaluating new Wilma(*f.p_) (e.g., an out-of-memory exception or an exception in Wilma ’s copy constructor ), this->p_ will be a dangling pointer — it will point to memory that is no longer valid. This can be solved by allocating the new objects before deleting the old objects.
Okay, okay, already; I’ll handle self-assignment. How do I do it?
You should worry about self assignment every time you create a class . This does not mean that you need to add extra code to all your classes: as long as your objects gracefully handle self assignment, it doesn’t matter whether you had to add extra code or not.
We will illustrate the two cases using the assignment operator in the previous FAQ :
If self-assignment can be handled without any extra code, don’t add any extra code. But do add a comment so others will know that your assignment operator gracefully handles self-assignment:
Example 1a:
Example 1b:
If you need to add extra code to your assignment operator, here’s a simple and effective technique:
Or equivalently:
By the way: the goal is not to make self-assignment fast. If you don’t need to explicitly test for self-assignment, for example, if your code works correctly (even if slowly) in the case of self-assignment, then do not put an if test in your assignment operator just to make the self-assignment case fast. The reason is simple: self-assignment is almost always rare, so it merely needs to be correct - it does not need to be efficient. Adding the unnecessary if statement would make a rare case faster by adding an extra conditional-branch to the normal case, punishing the many to benefit the few.
In this case, however, you should add a comment at the top of your assignment operator indicating that the rest of the code makes self-assignment is benign, and that is why you didn’t explicitly test for it. That way future maintainers will know to make sure self-assignment stays benign, or if not, they will need to add the if test.
I’m creating a derived class; should my assignment operators call my base class’s assignment operators?
Yes (if you need to define assignment operators in the first place).
If you define your own assignment operators, the compiler will not automatically call your base class’s assignment operators for you. Unless your base class’s assignment operators themselves are broken, you should call them explicitly from your derived class’s assignment operators (again, assuming you create them in the first place).
However if you do not create your own assignment operators, the ones that the compiler create for you will automatically call your base class’s assignment operators.
Please Login to submit a recommendation.
If you don’t have an account, you can register for free.
The rule of three/five/zero
Rule of three.
If a class requires a user-defined destructor , a user-defined copy constructor , or a user-defined copy assignment operator , it almost certainly requires all three.
Because C++ copies and copy-assigns objects of user-defined types in various situations (passing/returning by value, manipulating a container, etc), these special member functions will be called, if accessible, and if they are not user-defined, they are implicitly-defined by the compiler.
The implicitly-defined special member functions are typically incorrect if the class is managing a resource whose handle is an object of non-class type (raw pointer, POSIX file descriptor, etc), whose destructor does nothing and copy constructor/assignment operator performs a "shallow copy" (copy the value of the handle, without duplicating the underlying resource).
Classes that manage non-copyable resources through copyable handles may have to declare copy assignment and copy constructor private and not provide their definitions or define them as deleted. This is another application of the rule of three: deleting one and leaving the other to be implicitly-defined will most likely result in errors.
Rule of five
Because the presence of a user-defined destructor, copy-constructor, or copy-assignment operator prevents implicit definition of the move constructor and the move assignment operator , any class for which move semantics are desirable, has to declare all five special member functions:
Unlike Rule of Three, failing to provide move constructor and move assignment is usually not an error, but a missed optimization opportunity.
Rule of zero
Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle ). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators. [1]
This rule also appears in the C++ Core Guidelines as C.20: If you can avoid defining default operations, do .
When a base class is intended for polymorphic use, its destructor may have to be declared public and virtual. This blocks implicit moves (and deprecates implicit copies), and so the special member functions have to be declared as defaulted [2]
however, this makes the class prone to slicing, which is why polymorphic classes often define copy as deleted (see C.67: A polymorphic class should suppress copying in C++ Core Guidelines), which leads to the following generic wording for the Rule of Five:
- ↑ "Rule of Zero", R. Martinho Fernandes 8/15/2012
- ↑ "A Concern about the Rule of Zero", Scott Meyers, 3/13/2014

IMAGES
VIDEO
COMMENTS
RCA has multiple customer service numbers, each of which is assigned to a particular product line. RCA doesn’t operate a general customer service line, so customers must identify which product department they want to contact in advance.
Most Delta customers choose their seats when purchasing a ticket. Basic Economy customers are assigned seats by Delta and receive a seat assignment after check-in. These seat assignments are random, and there is no guarantee that members of...
When dealing with fractions, the order of operations states that multiplication or division is performed first, moving from left to right, and is followed by addition or subtraction, also moving from left to right.
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
To create a move assignment operator for a C++ class ... In the move assignment operator, add a conditional statement that performs no operation
Is there ever a situation where this == &rhs would be true? ? Class::operator=(Class&& rhs) { ? } c++ · c++11
The move assignment operator (operator=) is used to transfer resources from one DynamicArray object to another. It releases the current
The move constructor and move assignment operator are simple. Instead of deep copying the source object (a) into the implicit object, we simply
We continue our series on C++11 features you might have forgotten or never learned. Specifically, we will talk about the move constructor
Use Move Constructor and Move Assignment Operator - C++ Class. C++ examples for Class:Constructor. HOME · C++ · Class · Constructor. Description. Use Move
In C++, the assignment operator (operator=) is a special member ... In this case, you do not need to define a custom assignment operator.
} This is only valid for copy assignment. Self-assignment is not valid for move assignment. Why should I worry about “
... custom destructors, copy/move constructors or copy/move assignment operators. This rule also appears in the C++ Core Guidelines as C.20: If you can
In addition to the copy-constructor and copy-assignment, we can add a move-constructor and a move-assignment operator to our class. Instead of taking a