explicit copy constructor or implicit parameter by value

Posted by R Samuel Klatchko on Stack Overflow See other posts from Stack Overflow or by R Samuel Klatchko
Published on 2010-01-09T19:29:26Z Indexed on 2010/04/10 18:33 UTC
Read the original article Hit count: 337

I recently read (and unfortunately forgot where), that the best way to write operator= is like this:

foo &operator=(foo other)
{
    swap(*this, other);
    return *this;
}

instead of this:

foo &operator=(const foo &other)
{
    foo copy(other);
    swap(*this, copy);
    return *this;
}

The idea is that if operator= is called with an rvalue, the first version can optimize away construction of a copy. So when called with a rvalue, the first version is faster and when called with an lvalue the two are equivalent.

I'm curious as to what other people think about this? Would people avoid the first version because of lack of explicitness? Am I correct that the first version can be better and can never be worse?

© Stack Overflow or respective owner

Related posts about c++

Related posts about operators