c++standards

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:

Class_name instance_name1 = instance_name2;   

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!


Solution

  • 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:

    struct X {
        int a;
        // an assignment operator which is not a copy assignment operator
        X &operator=(int rhs) { a = rhs; return *this; }
        // a copy assignment operator
        X &operator=(const X &rhs) { a = rhs.a; return *this; }
        // another copy assignment operator
        volatile X &operator=(const volatile X &rhs) volatile { 
            a = rhs.a; 
            return *this; 
        }
    };
    

    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:

    X x;
    x = 4; // uses non-copy assignment operator
    X y;
    y = x; // uses copy assignment operator
    

    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.