Consider a piece of code like this:
struct B {
int c;
B() {
c = 20;
}
};
struct A {
boost::optional<B> m_b;
void f() {
B b;
this->m_b = b;
}
};
int main(void) {
A a;
a.f();
cout << a.m_b->c << endl;
}
Apparently, a.m_b still validly exists, after assigning a local variable b to m_b.
This kind of confuses me, because I thought assigning an object to boost::optional<> was just assigning the address that points to the object. Since in my example that object is b, which is a local variable, its address should be invalid after function f() is done.
Then why is a.m_b still alive? It should be pointing to an invalid address.
boost::optional‘soperator=will callB‘s copy constructor. If you insert this into yourstruct Byou can set a breakpoint on it to see what’s going on:Boost uses a placement new in its implementation, maybe this is what confuses you?