我想初始化一个派生类的成员变量,然后将它传递给基类构造函数。我想出了下面的解决方案(也在这里:http ://cpp.sh/4uu4q )
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;
}