分配结构的可选成员的最佳样式是什么?例如我有一个结构:
struct B{
public:
int x;
}
struct A{
public:
boost::optional<B> b;
};
void foo(){
A a;
a.b.x = 10; //Runtime exception because a.b is not initialized.
}
一种选择是定义临时 B 结构并将其分配给 A:
void foo(){
A a;
B tmp;
a.b = tmp;
a.b.x = 10; //OK.
}
或者:
void foo(){
A a;
a.b = B();
a.b.x = 10; //OK.
}
有没有更清晰的方法来做到这一点?