언급 한대로 무한 재귀가 있습니다. 그러나,에 추가, 여기 = 연산을 구현하는 절대 안전한 방법 :
struct T {
T(T const& other);
T& operator=(T copy) {
swap(*this, copy);
return *this;
}
friend void swap(T& a, T& b);
};
는 정확한 복사 ctor에 스왑 및 예외 안전성과 모든 가장자리 경우가 당신을 위해 처리됩니다 쓰기!
복사본 매개 변수는 값이으로 전달 된 다음 변경되었습니다. 현재 인스턴스가 파기해야하는 리소스는 복사본이 파괴 될 때 처리됩니다. 이것은 current recommendations을 따르고 self-assignment을 깨끗하게 처리합니다.그것은 수동으로 관리 회원 (페이지) 또는 RAII/SBRM 스타일의 구성원 (의) 중 하나와 함께 작동
#include <algorithm>
#include <iostream>
struct ConcreteExample {
int* p;
std::string s;
ConcreteExample(int n, char const* s) : p(new int(n)), s(s) {}
ConcreteExample(ConcreteExample const& other)
: p(new int(*other.p)), s(other.s) {}
~ConcreteExample() { delete p; }
ConcreteExample& operator=(ConcreteExample copy) {
swap(*this, copy);
return *this;
}
friend void swap(ConcreteExample& a, ConcreteExample& b) {
using std::swap;
//using boost::swap; // if available
swap(a.p, b.p); // uses ADL (when p has a different type), the whole reason
swap(a.s, b.s); // this 'method' is not really a member (so it can be used
// the same way)
}
};
int main() {
ConcreteExample a (3, "a"), b (5, "b");
std::cout << a.s << *a.p << ' ' << b.s << *b.p << '\n';
a = b;
std::cout << a.s << *a.p << ' ' << b.s << *b.p << '\n';
return 0;
}
알 수 있습니다.
아직 알 수 없습니다. 구조체가 템플릿입니까? 그래서 스왑으로 복사가 원래 것입니다 * this? – Tim
감사합니다. 스왑도 "복사"를 변경합니까? 이게 과제 이상인가요? – Tim