c++ - Copy Constructor invoked instead of assignment operator -
consider following self contained code.
#include <iostream> template<typename ty> class foo { private: ty m_data; public: foo() :m_data() {} foo(ty data) :m_data(data) {} template<typename u> foo& operator=(foo<u> rv) { m_data = rv.m_data; return *this; } private: foo(foo&); foo& operator=(foo&); }; int main() { foo<int> na(10); foo<int> nb; nb = foo<int>(10); // (1) foo<int>(10); // (2) } my understanding statement (1) assignment rather copy constructor. yet, when compiling (vc++ , g++), error message states, tries match copy constructor declared private.
1>source.cpp(23): error c2248: 'foo<int>::foo' : cannot access private member declared in class 'foo<int>' 1> source.cpp(16) : see declaration of 'foo<int>::foo' my question is, why try search copy constructor instead of assignment.
note, know assignment failing because (2) compiles fine without error.
there two issues:
- your private assignment operator
foo& operator=(foo&);takes non-const lvalue reference. means cannot selected overload innb = foo<int>(10);, because rhs rvalue - that leads template assignment operator being selected. takes argument value, requiring copy or move copy constructor.
if fix 1. take const reference, gcc gives following error:
error: 'foo& foo::operator=(const foo&) [with ty = int]' private
if fix 2. template assignment operator takes const reference, code compiles without errors.
Comments
Post a Comment