• C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Copy Constructor vs Assignment Operator in C++

Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them:

Copy constructor  Assignment operator 
It is called when a new object is created from an existing object, as a copy of the existing object This operator is called when an already initialized object is assigned a new value from another existing object. 
It creates a separate memory block for the new object. It does not create a separate memory block or new memory space.
It is an overloaded constructor. It is a bitwise operator. 
C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class. A bitwise copy gets created, if the Assignment operator is not overloaded. 

className(const className &obj) {

// body 

}

 

className obj1, obj2;

obj2 = obj1;

Consider the following C++ program. 

Explanation: Here, t2 = t1;  calls the assignment operator , same as t2.operator=(t1); and   Test t3 = t1;  calls the copy constructor , same as Test t3(t1);

Must Read: When is a Copy Constructor Called in C++?

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

cppreference.com

Copy constructors.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
/ types
types
Members
pointer
-declarations
(C++11)
specifier
specifier
Special member functions
(C++11)
(C++11)
Inheritance
specifier (C++11)
specifier (C++11)

A copy constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

Syntax Explanation Implicitly-declared copy constructor Implicitly-defined copy constructor Deleted copy constructor Trivial copy constructor Eligible copy constructor Notes Example Defect reports See also

[ edit ] Syntax

class-name  parameter-list  (1)
class-name  parameter-list  function-body (2)
class-name  single-parameter-list  (3) (since C++11)
class-name  parameter-list  (4) (since C++11)
class-name  class-name  parameter-list  function-body (5)
class-name  class-name  single-parameter-list  (6) (since C++11)
class-name - the class whose copy constructor is being declared
parameter-list - a non-empty satisfying all following conditions: , the first parameter is of type T&, const T&, volatile T& or const volatile T&, and .
single-parameter-list - a of only one parameter, which is of type T&, const T&, volatile T& or const volatile T& and does not have a default argument
function-body - the of the copy constructor

[ edit ] Explanation

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization ) from another object of the same type (unless overload resolution selects a better match or the call is elided ), which includes

  • initialization: T a = b ; or T a ( b ) ; , where b is of type T ;
  • function argument passing: f ( 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 no move constructor .

[ edit ] Implicitly-declared copy constructor

If no user-defined copy constructors are provided for a class type, the compiler will always declare a copy constructor as a non- explicit inline public member of its class. This implicitly-declared copy constructor has the form T :: T ( const T & ) if all of the following are true:

  • each direct and virtual base B of T has a copy constructor whose parameters are of type const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy constructor whose parameters are of type const M & or const volatile M & .

Otherwise, the implicitly-declared copy constructor is T :: T ( T & ) .

Due to these rules, the implicitly-declared copy constructor cannot bind to a volatile lvalue argument.

A class can have multiple copy constructors, e.g. both T :: T ( const T & ) and T :: T ( T & ) .

Even if some user-defined copy constructors are present, the user may still force the implicit copy constructor declaration with the keyword default.

(since C++11)

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

[ edit ] Implicitly-defined copy constructor

If the implicitly-declared copy constructor is not deleted, 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++11) . For union types, the implicitly-defined copy constructor copies the object representation (as by std::memmove ). For non-union class types, the constructor performs full member-wise copy of the object's direct base subobjects and member subobjects, in their initialization order, using direct initialization. For each non-static data member of a reference type, the copy constructor binds the reference to the same object or function to which the source reference is bound.

If this satisfies the requirements of a (until C++23) (since C++23), the generated copy constructor is constexpr.

The generation of the implicitly-defined copy constructor is deprecated if has a user-defined destructor or user-defined copy assignment operator.

(since C++11)

[ edit ] Deleted copy constructor

The implicitly-declared or explicitly-defaulted (since C++11) copy constructor for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

has a non-static data member of rvalue reference type. (since C++11)
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that
  • M has a destructor that is deleted or (since C++11) inaccessible from the copy constructor, or
  • the overload resolution as applied to find M 's copy constructor
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

The implicitly-declared copy constructor for class is defined as deleted if declares a or .

(since C++11)

[ edit ] Trivial copy constructor

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

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

A trivial copy constructor for a non-union class effectively copies every scalar subobject (including, recursively, subobject of subobjects and so forth) of the argument and performs no other action. However, padding bytes need not be copied, and even the object representations of the copied subobjects need not be the same as long as their values are identical.

TriviallyCopyable objects can be copied by copying their object representations manually, e.g. with std::memmove . All data types compatible with the C language (POD types) are trivially copyable.

[ edit ] Eligible copy constructor

A copy constructor is eligible if it is either user-declared or both implicitly-declared and definable.

(until C++11)

A copy constructor is eligible if it is not deleted.

(since C++11)
(until C++20)

A copy constructor is eligible if all following conditions are satisfied:

(if any) are satisfied. than any other copy constructor.
(since C++20)

Triviality of eligible copy constructors determines whether the class is an implicit-lifetime type , and whether the class is a trivially copyable type .

[ edit ] Notes

In many situations, copy constructors are optimized out even if they would produce observable side-effects, see copy elision .

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++98 the conditions where implicitly-declared copy constructors
are undefined did not consider multi-dimensional array types
consider these types
C++11 volatile members make copy non-trivial ( ) triviality not affected
C++11 X(X&) = default was non-trivial made trivial
C++20 a copy constructor was not eligible if there is
another copy constructor which is more constrained
but does not satisfy its associated constraints
it can be eligible in this case

[ edit ] See also

  • converting constructor
  • copy assignment
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • 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 4 June 2024, at 23:47.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Copy assignment operator

(C++20)
(C++20)
(C++11)
(C++11)
(C++11)
(C++17)
General
Members
pointer
(C++11)
specifier
specifier
Special member functions
(C++11)
(C++11)
Inheritance
(C++11)
(C++11)

A copy 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 , T & , const T & , volatile T & , or const volatile T & . For a type to be CopyAssignable , it must have a public copy assignment operator.

class_name class_name ( class_name ) (1)
class_name class_name ( const class_name ) (2)
class_name class_name ( const class_name ) = default; (3) (since C++11)
class_name class_name ( const class_name ) = delete; (4) (since C++11)

Explanation

  • Typical declaration of a copy assignment operator when copy-and-swap idiom can be used.
  • Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used (non-swappable type or degraded performance).
  • Forcing a copy assignment operator to be generated by the compiler.
  • Avoiding implicit copy assignment.

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type ( struct , class , or union ), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M & or const volatile M & .

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) . (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.)

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

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

Because the copy assignment operator 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 copy assignment operator

A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:

  • T has a user-declared move constructor;
  • T has a user-declared move assignment operator.

Otherwise, it is defined as defaulted.

A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:

  • T has a non-static data member of non-class type (or array thereof) that is const ;
  • T has a non-static data member of a reference type;
  • T has a non-static data member or a direct or virtual base class that cannot be copy-assigned (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function);
  • T is a union-like class , and has a variant member whose corresponding assignment operator is non-trivial.

Trivial copy assignment operator

The copy 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) , , and if it is defaulted, its signature is the same as implicitly-defined (until C++14) ;
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial;
has no non-static data members of -qualified type. (since C++14)

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

Implicitly-defined copy assignment operator

If the implicitly-declared copy 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 copy assignment copies the object representation (as by std::memmove ). For non-union class types ( class and struct ), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and copy assignment operator for class types.

The generation of the implicitly-defined copy assignment operator is deprecated (since C++11) if T has a user-declared destructor or user-declared copy constructor.

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 copy assignment operator (same applies to move assignment ).

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

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++14 operator=(X&) = default was non-trivial made trivial

This browser is no longer supported.

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

Explicitly Defaulted and Deleted Functions

  • 8 contributors

In C++11, defaulted and deleted functions give you explicit control over whether the special member functions are automatically generated. Deleted functions also give you simple language to prevent problematic type promotions from occurring in arguments to functions of all types—special member functions, and normal member functions and nonmember functions—which would otherwise cause an unwanted function call.

Benefits of explicitly defaulted and deleted functions

In C++, the compiler automatically generates the default constructor, copy constructor, copy-assignment operator, and destructor for a type if it doesn't declare its own. These functions are known as the special member functions , and they're what make simple user-defined types in C++ behave like structures do in C. That is, you can create, copy, and destroy them without extra coding effort. C++11 brings move semantics to the language and adds the move constructor and move-assignment operator to the list of special member functions that the compiler can automatically generate.

This is convenient for simple types, but complex types often define one or more of the special member functions themselves, and this can prevent other special member functions from being automatically generated. In practice:

If any constructor is explicitly declared, then no default constructor is automatically generated.

If a virtual destructor is explicitly declared, then no default destructor is automatically generated.

If a move constructor or move-assignment operator is explicitly declared, then:

No copy constructor is automatically generated.

No copy-assignment operator is automatically generated.

If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then:

No move constructor is automatically generated.

No move-assignment operator is automatically generated.

Additionally, the C++11 standard specifies the following additional rules:

  • If a copy constructor or destructor is explicitly declared, then automatic generation of the copy-assignment operator is deprecated.
  • If a copy-assignment operator or destructor is explicitly declared, then automatic generation of the copy constructor is deprecated.

In both cases, Visual Studio continues to automatically generate the necessary functions implicitly, and doesn't emit a warning by default. Since Visual Studio 2022 version 17.7, C5267 can be enabled to emit a warning.

The consequences of these rules can also leak into object hierarchies. For example, if for any reason a base class fails to have a default constructor that's callable from a deriving class—that is, a public or protected constructor that takes no parameters—then a class that derives from it can't automatically generate its own default constructor.

These rules can complicate the implementation of what should be straight-forward, user-defined types and common C++ idioms—for example, making a user-defined type noncopyable by declaring the copy constructor and copy-assignment operator privately and not defining them.

Before C++11, this code snippet was the idiomatic form of noncopyable types. However, it has several problems:

The copy constructor has to be declared privately to hide it, but because it's declared at all, automatic generation of the default constructor is prevented. You have to explicitly define the default constructor if you want one, even if it does nothing.

Even if the explicitly defined default constructor does nothing, the compiler considers it to be nontrivial. It's less efficient than an automatically generated default constructor and prevents noncopyable from being a true POD type.

Even though the copy constructor and copy-assignment operator are hidden from outside code, the member functions and friends of noncopyable can still see and call them. If they're declared but not defined, calling them causes a linker error.

Although this is a commonly accepted idiom, the intent isn't clear unless you understand all of the rules for automatic generation of the special member functions.

In C++11, the noncopyable idiom can be implemented in a way that is more straightforward.

Notice how the problems with the pre-C++11 idiom are resolved:

Generation of the default constructor is still prevented by declaring the copy constructor, but you can bring it back by explicitly defaulting it.

Explicitly defaulted special member functions are still considered trivial, so there's no performance penalty, and noncopyable isn't prevented from being a true POD type.

The copy constructor and copy-assignment operator are public but deleted. It's a compile-time error to define or call a deleted function.

The intent is clear to anyone who understands =default and =delete . You don't have to understand the rules for automatic generation of special member functions.

Similar idioms exist for making user-defined types that are nonmovable, that can only be dynamically allocated, or that can't be dynamically allocated. Each of these idioms have pre-C++11 implementations that suffer similar problems, and that are similarly resolved in C++11 by implementing them in terms of defaulted and deleted special member functions.

Explicitly defaulted functions

You can default any of the special member functions—to explicitly state that the special member function uses the default implementation, to define the special member function with a nonpublic access qualifier, or to reinstate a special member function whose automatic generation was prevented by other circumstances.

You default a special member function by declaring it as in this example:

Notice that you can default a special member function outside the body of a class as long as it's inlinable.

Because of the performance benefits of trivial special member functions, we recommend that you prefer automatically generated special member functions over empty function bodies when you want the default behavior. You can do this either by explicitly defaulting the special member function, or by not declaring it (and also not declaring other special member functions that would prevent it from being automatically generated.)

Deleted functions

You can delete special member functions and normal member functions and nonmember functions to prevent them from being defined or called. Deleting of special member functions provides a cleaner way of preventing the compiler from generating special member functions that you don't want. The function must be deleted as it's declared; it can't be deleted afterwards in the way that a function can be declared and then later defaulted.

Deleting of normal member function or nonmember functions prevents problematic type promotions from causing an unintended function to be called. This works because deleted functions still participate in overload resolution and provide a better match than the function that could be called after the types are promoted. The function call resolves to the more-specific—but deleted—function and causes a compiler error.

Notice in the preceding sample that calling call_with_true_double_only by using a float argument would cause a compiler error, but calling call_with_true_double_only by using an int argument wouldn't; in the int case, the argument will be promoted from int to double and successfully call the double version of the function, even though that might not be what you intend. To ensure that any call to this function by using a non-double argument causes a compiler error, you can declare a template version of the deleted function.

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

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Delete copy constructor and assignment [closed]

I am writing a program with C++ and since it is going to be big and a lot of people will edit this, I am going to use the MVC pattern. The question is very easy.

There is a controller that is the intermediate between the model (.cpp and .h files) and the view (made with Qt). Since the controller is only one and it has to manage everything during the lifetime of the app, do I have to deny copy constructor and copy assignment like this?

Is this still flexible? Because I don't see the sense of having 3 instances of a controller and each of them manage a different part of the program. There must be only one, am I correct?

Jamal's user avatar

  • 1 \$\begingroup\$ Looks like a syntax error to me - unless your implementation has a macro called deltete . \$\endgroup\$ –  Toby Speight Commented Dec 8, 2017 at 9:32

It sounds like what you want is a hard-enforced singleton.

With an interface like the following, you can provide a hard guarantee that only a single instance of Controller will ever exist:

I am personally partial to Meyer's singleton for the implementation:

// in .cpp file:

Not the answer you're looking for? Browse other questions tagged c++ mvc or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • How close would a quasar have to be to be seen with the naked eye?
  • How can I power both sides of breaker box with two 120 volt battery backups?
  • Can you be charged with breaking and entering if the door was open, and the owner of the property is deceased?
  • When selling a machine with proprietary software that links against an LGPLv3 library, do I need to give the customer root access?
  • Question about NMAP HTTP Verb Tampering
  • What does "that" in "No one ever meant that, Drax" refer to?
  • Mac Mini G4 not reinitialized
  • A manifold whose tangent space of a sum of line bundles and higher rank vector bundles
  • Can player build dungeons in D&D? I thought that was just a job for the DM
  • Why is で used with タイミング instead of に?
  • Were there any stone vessels (including mortars) made in Paleolithic?
  • When do people say "Toiletten" in the plural?
  • Is there a way to change a cantrip spell type to Necromancy in order to fulfil the requirement of the Death Domain Reaper ability for Clerics?
  • What is the reason for using decibels to measure sound?
  • How does a country without exit immigration check know you have overstayed?
  • Where am I wrong in my derivation of RC charging circuit equation?
  • Improve spacing around equality = and other math relation symbols
  • Can I convert 50 amp electric oven circuit to subpanel, and power oven plus water heater, plus maybe a car charger?
  • Using 50 Ω coax cable instead of passive probe
  • How to solve the intersection truncation problem of multiple \draw[thick, color=xxx] commands by color?
  • Does installing Ubuntu Deskto on Xubuntu LTS adopt the longer Ubuntu support period
  • ForeignFunctionLoad / RawMemoryAllocate and c-struct that includes an array
  • How to photograph the lettering on a bronze plaque?
  • Are there dedicated research facilities in the USA?

c delete copy constructor assignment operator

14.14 — Introduction to the copy constructor

The copy constructor

When an object is passed by value, the argument is copied into the parameter. When the argument and parameter are the same class type, the copy is made by implicitly invoking the copy constructor. Similarly, when an object is returned back to the caller by value, the copy constructor is implicitly invoked to make the copy.

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Assignment operator implicitly deleted

  Assignment operator implicitly deleted

c delete copy constructor assignment operator

is implicitly deleted because the definition would be ill-formed: Element{ ^~~~~~ Element.h:42:7: error: non- reference member , can
Element& Container:: [](ElementID input_ent_id) { ( Element& ent : ent_register) { (ent.getId() == input_ent_id) { ent; } } } Element& Container:: [](ElementID input_ent_id) { (Element& ent : ent_register) { (ent.getId() == input_ent_id) { ent; } } }
std::string& nm, EType ent_type) { Element ent(nm, ent_type, * , generateUniqueID()); ent_register.push_back(ent); ent.getId(); }
I think the issue is something to do with the constness of Element
reference member , can
Deleted implicitly-declared copy assignment operator

A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true:
• T has a user-declared move constructor;
• T has a user-declared move assignment operator.

Otherwise, it is defined as defaulted.

A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:

• T has a non-static data member of non-class type (or array thereof) that is const;

• T has a non-static data member or a direct or virtual base class that cannot be copy-assigned (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function);
• T is a union-like class, and has a variant member whose corresponding assignment operator is non-trivial.
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What is std::move(), and when should it be used?

  • What is it?
  • What does it do?
  • When should it be used?

Good links are appreciated.

  • move-semantics

Jan Schultke's user avatar

  • 64 Bjarne Stroustrup explains move in A Brief Introduction to Rvalue References –  DumbCoder Commented Aug 5, 2010 at 9:49
  • 2 Move semantics –  Basilevs Commented Sep 11, 2014 at 4:12
  • 23 This question is referring to std::move(T && t) ; there also exists a std::move(InputIt first, InputIt last, OutputIt d_first) which is an algorithm related to std::copy . I point it out so others aren't as confused as I was when first confronted with a std::move taking three arguments. en.cppreference.com/w/cpp/algorithm/move –  josaphatv Commented Oct 17, 2016 at 22:48
  • 2 Recommend reading this if you don't have much of an idea what lvalue and rvalue references mean internalpointers.com/post/… –  Karan Singh Commented Jun 25, 2020 at 15:22
  • 2 To clarify, this question is about the std::move from <utility> , not the std::move from <algorithm> . –  Adrian McCarthy Commented Apr 18, 2022 at 13:43

9 Answers 9

1. "what is it".

While std::move() is technically a function - I would say it isn't really a function . It's sort of a converter between ways the compiler considers an expression's value.

2. "What does it do?"

The first thing to note is that std::move() doesn't actually move anything . It changes an expression from being an lvalue (such as a named variable) to being an xvalue . An xvalue tells the compiler:

You can plunder me, move anything I'm holding and use it elsewhere (since I'm going to be destroyed soon anyway)".

in other words, when you use std::move(x) , you're allowing the compiler to cannibalize x . Thus if x has, say, its own buffer in memory - after std::move() ing the compiler can have another object own it instead.

You can also move from a prvalue (such as a temporary you're passing around), but this is rarely useful.

3. "When should it be used?"

Another way to ask this question is "What would I cannibalize an existing object's resources for?" well, if you're writing application code, you would probably not be messing around a lot with temporary objects created by the compiler. So mainly you would do this in places like constructors, operator methods, standard-library-algorithm-like functions etc. where objects get created and destroyed automagically a lot. Of course, that's just a rule of thumb.

A typical use is 'moving' resources from one object to another instead of copying. @Guillaume links to this page which has a straightforward short example: swapping two objects with less copying.

using move allows you to swap the resources instead of copying them around:

Think of what happens when T is, say, vector<int> of size n. In the first version you read and write 3*n elements, in the second version you basically read and write just the 3 pointers to the vectors' buffers, plus the 3 buffers' sizes. Of course, class T needs to know how to do the moving; your class should have a move-assignment operator and a move-constructor for class T for this to work.

einpoklum's user avatar

  • 23 For a long time I've heard of these move semantics, I never looked into them. From this description you've given it just seems like it's a shallow copy instead of a deep copy. –  Zebrafish Commented Dec 30, 2016 at 10:52
  • 50 @TitoneMaurice: Except that it's not a copy - as the original value is no longer usable. –  einpoklum Commented Dec 30, 2016 at 11:52
  • 15 @Zebrafish you couldn't be more wrong. A shallow copy leaves the original in the exact same state, a move usually results in the original being empty or in an otherwise valid state. –  rubenvb Commented Jan 10, 2018 at 22:38
  • 94 @rubenvb Zebra isn't entirely wrong. While it's true that the original cannabilised object is usually deliberately sabotaged to avoid confusing errors (e.g. set its pointers to nullptr to signal that it no longer owns the pointees), the fact that the whole move is implemented by simply copying a pointer from the source to the destination (and deliberately avoiding doing anything with the pointee) is indeed reminiscent of a shallow copy. In fact, I would go so far as to say that a move is a shallow copy, followed optionally by a partial self-destruct of the source. (cont.) –  Lightness Races in Orbit Commented Nov 1, 2018 at 18:54
  • 29 (cont.) If we permit this definition (and I rather like it), then @Zebrafish's observation isn't wrong, just slightly incomplete. –  Lightness Races in Orbit Commented Nov 1, 2018 at 18:55

Wikipedia Page on C++11 R-value references and move constructors

  • In C++11, in addition to copy constructors, objects can have move constructors. (And in addition to copy assignment operators, they have move assignment operators.)
  • The move constructor is used instead of the copy constructor, if the object has type "rvalue-reference" ( Type && ).
  • std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.

It's a new C++ way to avoid copies. For example, using a move constructor, a std::vector could just copy its internal pointer to data to the new object, leaving the moved object in an moved from state, therefore not copying all the data. This would be C++-valid.

Try googling for move semantics, rvalue, perfect forwarding.

Noch's user avatar

  • 47 Move-semantics require the moved object remain valid , which is not an incorrect state. (Rationale: It still has to destruct, make it work.) –  GManNickG Commented Aug 5, 2010 at 16:37
  • 19 @GMan: well, it has to be in a state that is safe to destruct, but, AFAIK, it does not have to be usable for anything else. –  Zan Lynx Commented Oct 4, 2011 at 19:15
  • 9 @ZanLynx: Right. Note that the standard library additionally requires moved objects be assignable, but this is only for objects used in the stdlib, not a general requirement. –  GManNickG Commented Oct 4, 2011 at 19:44
  • 34 -1 "std::move() is the C++11 way to use move semantics" Please fix that. std::move() is not the way to use move semantics, move semantics are performed transparently to the programmer. move its only a cast to pass a value from one point to another where the original lvalue will no longer be used. –  Manu343726 Commented Jul 3, 2014 at 19:35
  • 31 I'd go further. std::move itself does "nothing" - it has zero side effects. It just signals to the compiler that the programmer doesn't care what happens to that object any more. i.e. it gives permission to other parts of the software to move from the object, but it doesn't require that it be moved. In fact, the recipient of an rvalue reference doesn't have to make any promises about what it will or will not do with the data. –  Aaron McDaid Commented Aug 20, 2015 at 14:17

You can use move when you need to "transfer" the content of an object somewhere else, without doing a copy (i.e. the content is not duplicated, that's why it could be used on some non-copyable objects, like a unique_ptr). It's also possible for an object to take the content of a temporary object without doing a copy (and save a lot of time), with std::move.

This link really helped me out :

http://thbecker.net/articles/rvalue_references/section_01.html

I'm sorry if my answer is coming too late, but I was also looking for a good link for the std::move, and I found the links above a little bit "austere".

This puts the emphasis on r-value reference, in which context you should use them, and I think it's more detailed, that's why I wanted to share this link here.

q-l-p's user avatar

  • 31 Nice link. I always found the wikipedia article, and other links that I stumbled across rather confusing since they just throw facts at you, leaving it to you to figure out what the actual meaning/rationale is. While "move semantics" in a constructor is rather obvious, all those details about passing &&-values around are not... so the tutorial-style description was very nice. –  Christian Stieber Commented Jul 15, 2012 at 12:12

Q: What is std::move ?

A: std::move() is a function from the C++ Standard Library for casting to a rvalue reference.

Simplisticly std::move(t) is equivalent to:

An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.

An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:

As you can see, std::move returns T&& no matter if called with a value ( T ), reference type ( T& ), or rvalue reference ( T&& ).

Q: What does it do?

A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.

What it does not do:

  • Make a copy of the argument
  • Call the copy constructor
  • Change the argument object

Q: When should it be used?

A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

This begs the following follow-up questions for me:

What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.

What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.

Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.

In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged (rather than allocating a new instance).

Christopher Oezbek's user avatar

  • 16 Big +1 for code examples with semantics in comments. The other top answers define std::move using "move" itself - doesn't really clarify anything! --- I believe it's worth mentioning that not making a copy of the argument means that the original value cannot be reliably used. –  llf Commented Jun 7, 2018 at 18:48

std::move itself doesn't really do much. I thought that it called the moved constructor for an object, but it really just performs a type cast (casting an lvalue variable to an rvalue so that the said variable can be passed as an argument to a move constructor or assignment operator).

So std::move is just used as a precursor to using move semantics. Move semantics is essentially an efficient way for dealing with temporary objects.

Consider Object A = B + (C + (D + (E + F)));

This is nice looking code, but E + F produces a temporary object. Then D + temp produces another temporary object and so on. In each normal "+" operator of a class, deep copies occur.

For example

The creation of the temporary object in this function is useless - these temporary objects will be deleted at the end of the line anyway as they go out of scope.

We can rather use move semantics to "plunder" the temporary objects and do something like

This avoids needless deep copies being made. With reference to the example, the only part where deep copying occurs is now E + F. The rest uses move semantics. The move constructor or assignment operator also needs to be implemented to assign the result to A.

Dark Dududu's user avatar

  • 3 you spoke about move semantics . you should add to your answer as how std::move can be used because the question asks about that. –  Koushik Shetty Commented Jun 5, 2013 at 8:01
  • 2 @Koushik std::move doesnt do much - but is used to implement move semantics. If you don't know about std::move, you probably dont know move semantics either –  user929404 Commented Jun 5, 2013 at 8:56
  • 2 "doesnt do much"(yes just a static_cast to to a rvalue reference). what actually does it do and y it does is what the OP asked. you need not know how std::move works but you got to know what move semantics does. furthermore, "but is used to implement move semantics" its the otherway around. know move semantics and you'l understand std::move otherwise no. move just helps in movement and itself uses move semantics. std::move does nothing but convert its argument to rvalue reference, which is what move semantics require. –  Koushik Shetty Commented Jun 5, 2013 at 9:08
  • 11 "but E + F produces a temporary object" - Operator + goes left to right, not right to left. Hence B+C would be first! –  Ajay Commented Oct 15, 2015 at 7:20
  • only your answer explained it to me –  Ulterior Commented Nov 10, 2020 at 11:53

"What is it?" and "What does it do?" has been explained above.

I will give a example of "when it should be used".

For example, we have a class with lots of resource like big array in it.

output as below:

We can see that std::move with move constructor makes transform resource easily.

Where else is std::move useful?

std::move can also be useful when sorting an array of elements. Many sorting algorithms (such as selection sort and bubble sort) work by swapping pairs of elements. Previously, we’ve had to resort to copy-semantics to do the swapping. Now we can use move semantics, which is more efficient.

It can also be useful if we want to move the contents managed by one smart pointer to another.

  • https://www.learncpp.com/cpp-tutorial/15-4-stdmove/

Lightness Races in Orbit's user avatar

std::move itself does nothing rather than a static_cast . According to cppreference.com

It is exactly equivalent to a static_cast to an rvalue reference type.

Thus, it depends on the type of the variable you assign to after the move , if the type has constructors or assign operators that takes a rvalue parameter, it may or may not steal the content of the original variable, so, it may leave the original variable to be in an unspecified state :

Unless otherwise specified, all standard library objects that have been moved from being placed in a valid but unspecified state.

Because there is no special move constructor or move assign operator for built-in literal types such as integers and raw pointers, so, it will be just a simple copy for these types.

Yoon5oo's user avatar

std::move simply casts a variable to an rvalue reference. This rvalue reference is notated with &&. Let's say you have a class Foo and you instantiate an object like this

If you then write

that's the same thing as If I wrote

std::move replaces this cast to an rvalue reference. The reason why you would want to write either of the previous 2 lines of code is that if you write

The copy constructor will be called. Let's say Foo instances have a pointer to some data on the heap which they own. In Foo's destructor that data on the heap gets deleted. If you want to distinghuish between copying the data from the heap and taking ownership of that data, you can write a constructor which takes in const Foo& and that constructor can perform the deep copy. Then you can write a constructor which takes in an rvalue reference (Foo&&) and this constructor can simply rewire the pointers. This constructor which takes in Foo&& will be called when you write

and when you write

zast99's user avatar

  • I think it could be misleading using the C-style cast " (Foo&&) ", since it provides little compile-time guarantee in contrast to using static_cast as already suggested by @ChristopherOezbeck. More info here . Otherwise this answer doesn't add much which hasn't already been covered. –  alexpanter Commented Feb 21, 2023 at 14:51

Here is a full example, using std::move for a (simple) custom vector

Expected output:

Compile as:

Goblinhack's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ c++11 move-semantics c++-faq stdmove or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • What makes a homepage useful for logged-in users
  • The [lib] tag is being burninated

Hot Network Questions

  • How to optimize performance with DeleteDuplicates?
  • Reversing vowels in a string
  • Can a country refuse to deliver a person accused of attempted murder?
  • Souls originating from Adam HaRishon
  • Visa requirements for British passport holders going to Ghana via Brussels
  • Does installing Ubuntu Deskto on Xubuntu LTS adopt the longer Ubuntu support period
  • Do thermodynamic cycles occur only in human-made machines?
  • Are there rules for gender of durations?
  • Tour de France General Classification time
  • What makes Python better suited to quant finance than Matlab / Octave, Julia, R and others?
  • Is it possible for some p-values to be impossible? (because statistic generated by parametric bootstrap is mostly the same value.)
  • Why did the general choose this as the exact time of attack?
  • Why was this a draw? What move I supposed to play to win?
  • Job talk Q&A: handling the room vs. being respectful
  • How do we define addition?
  • Optimizing Pi Estimation Code
  • How does a country without exit immigration check know you have overstayed?
  • Is a desert planet with a small habitable area possible?
  • How do I drill a 60cm hole in a tree stump, 4.4 cm wide?
  • When do people say "Toiletten" in the plural?
  • Why did Nigel Farage choose Clacton as the constituency to campaign in?
  • Are there alternative statistics to a p-value in NHST?
  • Book about a boy who becomes a sorcerer
  • Confusion on defining uniform distribution on hypersphere and its sampling problem

c delete copy constructor assignment operator

COMMENTS

  1. When to delete copy constructor and assignment operator?

    Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour. Probably the simplest example is the class std::unique_ptr. As the name implies, it has unique ...

  2. c++

    The presence of the copy versions will prevent the implicit-declaration of the move constructor and move assignment operator, and declaring one form of a copy special member function suppresses the implicit-declaration of other forms.

  3. Copy assignment operator

    the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial. A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.

  4. Copy constructors and copy assignment operators (C++)

    Use an assignment operator operator= that returns a reference to the class type and takes one parameter that's passed by const reference—for example ClassName& operator=(const ClassName& x);. Use the copy constructor. If you don't declare a copy constructor, the compiler generates a member-wise copy constructor for you.

  5. Copy constructors, assignment operators,

    Copy constructors, assignment operators, and exception safe assignment. Score: 4.3/5 (3169 votes) ... instance is responsible for calling delete on the pointer at some point (probably the destructor). If two objects end up calling delete on the same non-NULL pointer, heap corruption results.

  6. Copy Constructor vs Assignment Operator in C++

    C++ compiler implicitly provides a copy constructor, if no copy constructor is defined in the class. A bitwise copy gets created, if the Assignment operator is not overloaded. Consider the following C++ program. Explanation: Here, t2 = t1; calls the assignment operator, same as t2.operator= (t1); and Test t3 = t1; calls the copy constructor ...

  7. Copy constructors

    The implicitly-declared (or defaulted on its first declaration) copy constructor has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17). [] Implicitly-defined copy constructoIf the implicitly-declared copy constructor is not deleted, it is defined (that is, a function body is generated and compiled) by the compiler if ...

  8. PDF Copy Constructors and Assignment Operators

    In this case, since two has already been initialized in the previous line, C++ will use the MyClass assignment operator to assign two the value of the variable one. It can be tricky to differentiate between code using the assignment operator and code using the copy constructor. For example, if we rewrite the above code as MyClass one; MyClass ...

  9. Copy assignment operator

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

  10. 21.12

    21.12 — Overloading the assignment operator. Alex November 27, 2023. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  11. C++ at Work: Copy Constructors, Assignment Operators, and More

    In C++, assignment and copy construction are different because the copy constructor initializes uninitialized memory, whereas assignment starts with an existing initialized object. If your class contains instances of other classes as data members, the copy constructor must first construct these data members before it calls operator=.

  12. Copy assignment operator

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

  13. Copy constructors, assignment operators,

    A copy constructor is a special constructor for a class/struct that is. used to make a copy of an existing instance. The copy constructor for. the class MyClass must have the following signature, according to the. C++ standard: MyClass( const MyClass& other ); Note that none of the following constructors, despite the fact that.

  14. Explicitly Defaulted and Deleted Functions

    Benefits of explicitly defaulted and deleted functions. In C++, the compiler automatically generates the default constructor, copy constructor, copy-assignment operator, and destructor for a type if it doesn't declare its own. These functions are known as the special member functions, and they're what make simple user-defined types in C++ ...

  15. c++

    The usual way is to declare the copy constructor and the assignment operator to be private, which causes compilation errors, like Als explained. Deriving from boost::noncopyable will do this job ... If you are working with C++11 you can also delete your copy constructor: class nocopy { nocopy( nocopy const& ) = delete; }; Share. Improve this ...

  16. c++

    There is a controller that is the intermediate between the model (.cpp and .h files) and the view (made with Qt). Since the controller is only one and it has to manage everything during the lifetime of the app, do I have to deny copy constructor and copy assignment like this? class Controller {. public: Controller(const Controller& x) = deltete;

  17. 14.14

    The rule of three is a well known C++ principle that states that if a class requires a user-defined copy constructor, destructor, or copy assignment operator, then it probably requires all three. In C++11, this was expanded to the rule of five, which adds the move constructor and move assignment operator to the list.

  18. PDF Copy Constructors and Assignment Operators

    using the copy constructor. What C++ Does For You Unless you specify otherwise, C++ will automatically provide objects a basic copy constructor and assignment operator that simply invoke the copy constructors and assignment operators of all the class's data members. In many cases, this is exactly what you want. For example, consider the ...

  19. Assignment operator implicitly deleted

    A implicitly-declared copy assignment operator for class T is defined as deleted if any of the following is true: • T has a user-declared move constructor; • T has a user-declared move assignment operator. Otherwise, it is defined as defaulted. A defaulted copy assignment operator for class T is defined as deleted if any of the following is ...

  20. c++

    If you declare a copy constructor (even if you define it as deleted in the declaration), no move constructor will be declared implicitly.Cf. C++11 12.8/9: If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if — X does not have a user-declared copy constructor,

  21. c++

    Say I have a type that can only be moved (copy constructor and assignment operator have been deleted): struct FooBar { int a; int b; FooBar& operator = (const FooBar& other) = ...

  22. c++

    Please tell me how I can correct this piece of code so that the cookie_name_t class does not use a copy constructor and an assignment constructor. When I do the following: cookie_name(cookie_name const &) = delete; cookie_name &operator=(cookie_name const &) = delete; in the cookie_name_t class, the code not compiling.