Should the copy operator be set to const or by value?

Before C ++ 11, it was always the case that the copy assignment operator should always follow a const reference, for example:

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

However, with the introduction of assignment operators and move constructors, it seems that some people advocate using pass by value instead of assigning a copy. You must also add a move destination operator:

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

The above implementation of the statement is as follows:

 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 good to use pass by value when creating a copy assignment operator for C ++ 11? Under what circumstances should I do this?

+7
c ++ assignment-operator c ++ 11 move-semantics
source share
1 answer

Before C ++ 11, it was always the case that the copy assignment operator should always follow the const link

This is not true. The best approach has always been to use the idioms of copy and swap and what you see here (although the implementation in the body is suboptimal).

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

+11
source share

All Articles