What is the best style for assigning an optional member of structure? For example I have a struct:
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.
}
One option is to define temporary B struct and assign it to A:
void foo(){
A a;
B tmp;
a.b = tmp;
a.b.x = 10; //OK.
}
or:
void foo(){
A a;
a.b = B();
a.b.x = 10; //OK.
}
Is there a clearer way to do this?
You have no choice but to initialize it before using it. If you don't, you'll have an assertion fail which will cause a termination.
But if you are asking about ways to initialize it, there are a lot of them:
a.b = B{10}
as it is POD-type.a.b = B()
as you did already (works always and not only for POD-types).a.b = B(10)
. But still, you always have to create an object and assign to it. So, you may do either implicit or explicit creation of the object, but you must do it.emplace()
method that does the same for you: a.b.emplace()
.