Search code examples
c++boost-optional

Assigning member in optional structure memeber


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?


Solution

  • 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:

    1. a.b = B{10} as it is POD-type.
    2. a.b = B() as you did already (works always and not only for POD-types).
    3. Create a constructor and make it like 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.
    4. In boost 1.56, as @n.m told, here is an emplace() method that does the same for you: a.b.emplace().