• 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 the copy assignement operator?

At the present moment I am reading C++ 11 standard , in which (chapter 12) among special member functions is mentioned ?copy? assignment operator .

I have already faced with operator= , which is simply assignment operator

My first guess was that it is used in statements like this:

when an object is created and initialized simultaneously, I checked my assumption and got that this done by means of copy constructor(which was expected).

So, what for copy assignment operator is used, how to declare it and can you give me some example of its usage. Thanks in advance!

Community's user avatar

3 Answers 3

It's defined in the standard, 12.8/17:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X , X& , const X& , volatile X& or const volatile X& .

So for example:

Assignment operators are used when you assign to an object. You might think that doesn't say much, but your example code Class_name instance_name1 = instance_name2; doesn't assign to an object, it initializes one. The difference is in the grammar of the language: in both cases the = symbol precedes something called an initializer-clause , but Class_name instance_name1 = instance_name2; is a definition, whereas instance_name1 = instance_name2; on its own after instance_name1 has been defined is an expression-statement containing an assignment-expression . Assignment-expressions use assignment operators, definitions use constructors.

If the usual rules for overload resolution select an assignment operator that is a copy assignment operator, then that's when a copy assignment operator is used:

The reason there's a distinction between copy and non-copy assignment operators, is that if you declare a copy assignment operator, that suppresses the default copy assignment operator. If you declare any non-copy assignment operators, they don't suppress the default copy assignment.

Steve Jessop's user avatar

  • 1 Thank you very much for detailed explanation! Now copy assignement operator and it`s usage makes sense for me. –  spin_eight Commented Nov 7, 2012 at 10:38
  • It may be worth pointing out that the reason the standard uses the expression "copy assignment operator", and not just "assignment operator", is that it isn't unusual for classes to define assignment from some other type. For example, std::string has an assignment operator which takes a char const* (and so isn't a copy assignment operator. –  James Kanze Commented Feb 16 at 10:19

They are the same most of the time. Pedantically, the standard says:

13.5.3 Assignment [over.ass]

2) Any assignment operator, even the copy and move assignment operators, can be virtual.

(correct reference in Steve's answer)

Which leads us to believe that an assignment operator can exist without being a copy or move one.

The example given is:

which makes me believe the first one is a simple assignment operator, while the second is the copy assignment operator. This also preserves the nomenclature used by the copy constructor.

So, I'd say a copy assignment operator is an assignment operator that takes as parameter a reference (or object) of the same type.

Luchian Grigore's user avatar

The assignment operator is = , and you can overload it like so:

In this case I've made it take int , which is pretty unusual and probably not desirable. Usually you write a copy assignment operator , which means it takes a reference to a T :

Lightness Races in Orbit'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++ standards or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Can someone help me identify this plant?
  • What mode of transport is ideal for the cold post-apocalypse?
  • Why didn't Walter White choose to work at Gray Matter instead of becoming a drug lord in Breaking Bad?
  • Unstable output C++: running the same thing twice gives different output
  • Conditional environment using package option
  • The minimal Anti-Sudoku
  • Repeats: Simpler at the cost of more redundant?
  • Is a user considered liable if its user accounts on social networks are hacked and used to post illegal content?
  • A study on the speed of gravity
  • Clarification on Counterfactual Outcomes in Causal Inference
  • Inaccurate group pace
  • Should I pay off my mortgage if the cash is available?
  • Where is the 6D-QSAR software Quasar(X) available?
  • Can you bring a cohort back to life?
  • With 42 supernovae in 37 galaxies, how do we know SH0ES results is robust?
  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Making blackberry Jam with fully-ripe blackberries
  • Guitar amplifier placement for live band
  • Why would Space Colonies even want to secede?
  • When is internal use internal (considering licenses and their obligations)?
  • Is an invalid date considered the same as a NULL value?
  • Is it illegal to allow (verbally) someone to do action that may kill them?
  • Get the first character of a string or macro
  • Why HIMEM was implemented as a DOS driver and not a TSR

copy assignment operator reference member

cppreference.com

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.

Syntax Explanation Implicitly-declared copy assignment operator Deleted implicitly-declared copy assignment operator Trivial copy assignment operator Implicitly-defined copy assignment operator Notes Example Defect reports

[ edit ] Syntax

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)

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

[ edit ] 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.

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

[ 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++14 operator=(X&) = default was non-trivial made trivial
  • Pages with unreviewed CWG DR marker
  • 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 9 January 2019, at 07:16.
  • This page has been accessed 570,566 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.

Copy constructors and copy assignment operators (C++)

  • 8 contributors

Starting in C++11, two kinds of assignment are supported in the language: copy assignment and move assignment . In this article "assignment" means copy assignment unless explicitly stated otherwise. For information about move assignment, see Move Constructors and Move Assignment Operators (C++) .

Both the assignment operation and the initialization operation cause objects to be copied.

Assignment : When one object's value is assigned to another object, the first object is copied to the second object. So, this code copies the value of b into a :

Initialization : Initialization occurs when you declare a new object, when you pass function arguments by value, or when you return by value from a function.

You can define the semantics of "copy" for objects of class type. For example, consider this code:

The preceding code could mean "copy the contents of FILE1.DAT to FILE2.DAT" or it could mean "ignore FILE2.DAT and make b a second handle to FILE1.DAT." You must attach appropriate copying semantics to each class, as follows:

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. Similarly, if you don't declare a copy assignment operator, the compiler generates a member-wise copy assignment operator for you. Declaring a copy constructor doesn't suppress the compiler-generated copy assignment operator, and vice-versa. If you implement either one, we recommend that you implement the other one, too. When you implement both, the meaning of the code is clear.

The copy constructor takes an argument of type ClassName& , where ClassName is the name of the class. For example:

Make the type of the copy constructor's argument const ClassName& whenever possible. This prevents the copy constructor from accidentally changing the copied object. It also lets you copy from const objects.

Compiler generated copy constructors

Compiler-generated copy constructors, like user-defined copy constructors, have a single argument of type "reference to class-name ." An exception is when all base classes and member classes have copy constructors declared as taking a single argument of type const class-name & . In such a case, the compiler-generated copy constructor's argument is also const .

When the argument type to the copy constructor isn't const , initialization by copying a const object generates an error. The reverse isn't true: If the argument is const , you can initialize by copying an object that's not const .

Compiler-generated assignment operators follow the same pattern for const . They take a single argument of type ClassName& unless the assignment operators in all base and member classes take arguments of type const ClassName& . In this case, the generated assignment operator for the class takes a const argument.

When virtual base classes are initialized by copy constructors, whether compiler-generated or user-defined, they're initialized only once: at the point when they are constructed.

The implications are similar to the copy constructor. When the argument type isn't const , assignment from a const object generates an error. The reverse isn't true: If a const value is assigned to a value that's not const , the assignment succeeds.

For more information about overloaded assignment operators, see Assignment .

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

IMAGES

  1. PPT

    copy assignment operator reference member

  2. PPT

    copy assignment operator reference member

  3. C++ : Overload copy assignment operator for a member struct of a non

    copy assignment operator reference member

  4. copy operations in python

    copy assignment operator reference member

  5. How to overload the member copy assignment operator as part of implementing the rule of three in C++

    copy assignment operator reference member

  6. Copy Constructor and Copy Assignment Operator (Contd.) (Lecture 28)

    copy assignment operator reference member