아래의 복사 생성자가 제대로 작동하지만 복사 할당 연산자가 잘못되었음을 이해하지 못합니다.다중 상속을 사용하는 복사 할당 연산자
#include <iostream>
template <typename... Ts> class foo;
template <typename Last>
class foo<Last> {
Last last;
public:
foo (Last r) : last(r) { }
foo() = default;
foo (const foo& other) : last(other.last) { }
foo& operator= (const foo& other) {
last = other.last;
return *this;
}
};
template <typename First, typename... Rest>
class foo<First, Rest...> : public foo<Rest...> {
First first;
public:
foo (First f, Rest... rest) : foo<Rest...>(rest...), first(f) { }
foo() = default;
foo (const foo& other) : foo<Rest...>(other), first(other.first) { std::cout << "[Copy constructor called]\n"; }
foo& operator= (const foo& other) { // Copy assignment operator
if (&other == this)
return *this;
first = other.first;
return foo<Rest...>::operator= (other);
}
};
int main() {
const foo<int, char, bool> a(4, 'c', true);
foo<int, char, bool> b = a; // Copy constructor works fine.
foo<int, char, bool> c;
// c = a; // Won't compile.
}
오류 메시지 :
error: invalid initialization of reference of type 'foo<int, char, bool>&' from expression of type 'foo<char, bool>'
return foo<Rest...>::operator= (other);
^
누군가가 여기에 문제를 지적 할 수 있습니까?
왜 복사 및 스왑을 사용하지 않습니까? 스왑 가능하지 않거나 측정 가능한 성능 문제가 아닌'T '를 기대합니까? –