짧은 답변 : 당신은 D에서 작업을 반복해야합니다 예
긴 대답 :
파생 클래스 'D'는 컴파일러에 의해 생성 한 후 새로운 멤버 변수 기본 버전 (포함하지 않는 경우해야 잘 작동). 기본 Copy 생성자는 부모 복사 생성자를 호출하고 기본 할당 연산자는 부모 할당 연산자를 호출합니다.
하지만 'D'클래스에 리소스가 포함 된 경우 약간의 작업이 필요합니다. 그들은 기본부터 건설 복사되도록
B(const B& b){(*this) = b;}
D(const D& d){(*this) = d;}
는 일반적으로 생성자 체인을 복사
나는 조금 이상한 당신의 복사 생성자를 찾을 수 있습니다. 여기서 할당 연산자를 호출하기 때문에 복사 생성자는 기본 생성자를 호출하여 개체를 맨 아래부터 위로 초기화해야합니다. 그런 다음 할당 연산자를 사용하여 다시 아래로 이동합니다. 이것은 다소 비효율적 인 것처럼 보인다.
이제 과제를 수행 할 때 아래에서 위로 (또는 위에서 아래로) 복사하는 것이지만 그렇게하는 것은 어렵고 강력한 예외 보장을 제공합니다. 어느 시점에서든 리소스가 복사되지 않고 예외가 발생하면 개체가 불확실한 상태가됩니다 (이는 나쁜 것입니다).
일반적으로 나는 다른 방법으로 처리 한 것을 보았습니다.
할당 연산자는 복사 생성자 및 스왑으로 정의됩니다. 이것은 강력한 예외 보장을 제공하기 쉽게하기 때문입니다. 나는 당신이 주위에 이런 방식으로 강한 보증을 제공 할 수있을 것이라고 생각하지 않는다. (틀릴 수도있다.)
class X
{
// If your class has no resources then use the default version.
// Dynamically allocated memory is a resource.
// If any members have a constructor that throws then you will need to
// write your owen version of these to make it exception safe.
X(X const& copy)
// Do most of the work here in the initializer list
{ /* Do some Work Here */}
X& operator=(X const& copy)
{
X tmp(copy); // All resource all allocation happens here.
// If this fails the copy will throw an exception
// and 'this' object is unaffected by the exception.
swap(tmp);
return *this;
}
// swap is usually trivial to implement
// and you should easily be able to provide the no-throw guarantee.
void swap(X& s) throws()
{
/* Swap all members */
}
};
X에서 클래스 D를 파생해도이 패턴에는 영향을주지 않습니다.
틀림없이 기본 클래스로 명시 적으로 호출하여 약간의 작업을 반복해야하지만 이는 비교적 간단합니다.
class D: public X
{
// Note:
// If D contains no members and only a new version of foo()
// Then the default version of these will work fine.
D(D const& copy)
:X(copy) // Chain X's copy constructor
// Do most of D's work here in the initializer list
{ /* More here */}
D& operator=(D const& copy)
{
D tmp(copy); // All resource all allocation happens here.
// If this fails the copy will throw an exception
// and 'this' object is unaffected by the exception.
swap(tmp);
return *this;
}
// swap is usually trivial to implement
// and you should easily be able to provide the no-throw guarantee.
void swap(D& s) throws()
{
X::swap(s); // swap the base class members
/* Swap all D members */
}
};
, 당신은 B :: 연산자를 사용하여 '사용할 수 =;'할당 연산자를 상속하지만, 복사 및 이동 생성자는 상속 될 수 없습니다하는 방법 : https://stackoverflow.com/q/5,447,906분의 49,045,026 –