Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should copy assignment operator pass by const reference or by value?

Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference, like so:

template <typename T>
ArrayStack<T>& operator= (const ArrayStack& other);

However, with the introduction of move assignment operators and constructors, it seems that some people are advocating using pass by value for copy assignment instead. A move assignment operator also needs to be added:

template <typename T>
ArrayStack<T>& operator= (ArrayStack other);
ArrayStack<T>& operator= (ArrayStack&& other);

The above 2 operator implementation looks like this:

template <typename T>
ArrayStack<T>& ArrayStack<T>::operator =(ArrayStack other)
{
    ArrayStack tmp(other);
    swap(*this, tmp);
    return *this;
}

template <typename T>
ArrayStack<T>& ArrayStack<T>::operator =(ArrayStack&& other)
{
    swap(*this, other);
    return *this;
}

Is it a good idea to use pass by value when creating copy assignment operator for C++11 onwards? Under what circumstances should I do so?

like image 772
Mantracker Avatar asked Aug 06 '16 20:08

Mantracker


People also ask

Does const reference make a copy?

Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function.

Why do we return reference in copy assignment operator?

A bit of clarification as to why it's preferable to return by reference for operator= versus return by value --- as the chain a = b = c will work fine if a value is returned. If you return a reference, minimal work is done. The values from one object are copied to another object.

How do you define copy assignment operator?

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.

What is true about the assignment (=) operator?

The simple assignment operator "=" is used to store the value of its right-hand operand into the memory location denoted by the left-hand operand. The result is its return value.


1 Answers

Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference

That is not true. The best approach has always been to use the copy-and-swap idiom, and that's what you're seeing here (although the implementation in the body is sub-optimal).

If anything, this is less useful in C++11 now that you have a move assignment operator too.

like image 143
Lightness Races in Orbit Avatar answered Sep 28 '22 19:09

Lightness Races in Orbit