user3560270
user3560270

Reputation: 443

c++ copy-assignment move-assignment ambiguity

In C++11, we get an ambiguity error from the compiler (g++) if we make the following definitions:

C& operator=(C rhs)
{
    swap(*this, rhs);
    return *this;
}

C& operator=(C&& rhs)
{
    swap(*this, rhs);
    return *this;
}

It is not entirely clear to me why there is an ambiguity. In my understanding, the compiler can tell apart what is an rvalue object and what is not at compile time. So it could make a decision to call the latter for rvalue objects and the former for lvalue objects. I am probably missing something basic but an explanation would be great.

Upvotes: 2

Views: 369

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38341

The argument must be passed through const reference to resolve the ambiguity.

C& operator=(const C& rhs)
{
    swap(*this, C(tmp));
    return *this;
}

Since your class C has a moving constructor C::C(C&&) (I think it is so, you did not provide Minimal, Complete, and Verifiable example) then it causes the ambiguity between operator=(C rhs) and operator=(C&& rhs).

Upvotes: 1

Related Questions