파생 클래스의 멤버 변수를 초기화하고 그 후에 기본 클래스 생성자에 전달하고 싶습니다. 아래 해결책을 생각해 냈습니다. (여기도 : http://cpp.sh/4uu4q)Initialize 기본 클래스 생성자를 호출하기 전에 파생 클래스 멤버 변수를 초기화합니다. 이 UB인가?
1) 다음 코드에 정의되거나 정의되지 않은 동작 (UB)이 있습니까?
2) 잘못된 디자인을 표시하려고합니까?
struct Data {
int fValue;
Data(int value = -1) : fValue(value)
{}
};
struct Base {
Base(const std::unique_ptr<Data> & derivedData) {
std::cout << "Constructing Base derivedData=" << derivedData->fValue << std::endl;
}
};
struct Derived : public Base {
std::unique_ptr<Data> fData = std::move(fData);
Derived() : Base(ConstructData())
{}
const std::unique_ptr<Data> & ConstructData() {
fData.release();
fData.reset(new Data(777));
std::cout << "in ConstructData: fData->fValue =" << fData->fValue << std::endl;
return fData;
}
};
int main() {
Derived d;
std::cout << "In main: d.fData->fValue =" << d.fData->fValue << std::endl;
return 0;
}
2) 네, 기본 클래스가 생성자에서 파생 된 클래스에 대해 알아야하는 이유는 무엇입니까? – user463035818
파생 클래스는 기본 클래스가 생성 될 때까지 생성되지 않습니다. 이것은 UB입니다. –
생성자가 호출되기 전에 fData를 조작하므로 UB입니다. –