Search code examples
c++templatesvisual-studio-2013assignment-operatorrvalue-reference

Template assignment operator with rvalue reference argument behaves differently with vs2013 and gcc


Why does the following code

#include <iostream>

struct A {
    template<typename T>
    A &operator=(T &&rhs) {
        std::cout << "A::operator= called" << std::endl;
        return *this;
    }
};

int main() {
    A a1;
    a1 = A();
    return 0;
}

print A::operator= called using Visual Studio Express 2013 but prints nothing when compiled with gcc-4.9.1.

What would be the correct behavior?

Edit: Template assignment operator overloading mystery does not address VS/gcc compiler differences.


Solution

  • GCC is correct. Your type has an implicitly declared move assignment operator, which is a better match than the template.

    If you cause the implicit move assignment to be suppressed, e.g. by adding a user-declared destructor, then your template will be used.