【发布时间】:2019-02-25 15:03:05
【问题描述】:
让我们考虑在执行类S 的构造函数期间,似乎可以使用另一个构造函数构造S。一种解决方案可能是在this 新建一个展示位置以重复使用存储:
struct S{
unsigned int j; //no const neither reference non static members
S(unsigned int i){/*...*/}
S(int i){
if (i>=0) {
new (this) S(static_cast<unsigned int>(i));
return;}
/*...*/
}
};
int i=10;
S x{i};//is it UB?
存储重用在[basic.life] 中定义。在构造函数执行期间(重新)使用存储时,我不知道如何阅读本节。
【问题讨论】:
-
使用委托构造函数和/或工厂?
-
@Jarod42 问题是这些都是无条件的。 OP 正试图根据运行时参数值仅委托某些时间。
-
@Angew
S(int i) : S(MakeS(i)) {}带有移动构造函数(或完全省略:-))。 -
构造函数将是错误的地方(在运行时完成时),因此您必须求助于类似工厂的方法
-
if (i>=0) j = static_cast<unsigned int>(i); else j = ....也许?
标签: c++ constructor language-lawyer