3

Given the following code sample:

boost::optional< int > opt;
opt = 12;
int* p( &*opt );
opt = 24;
assert( p == &*opt );

Is there any guarantee that the assert will always be valid?

Julien
  • 2,139
  • 1
  • 19
  • 32

1 Answers1

3

yes it's a guarantee. The T of a boost::optional<T> is a logically a private member of the optional.

the code above is logically equivalent to:

bool opt_constructed = false;
int opt_i; // not constructed

new int (&opt_i)(12); opt_constructed = true; // in-place constructed

int*p = &opt_i;

opt_i = 24;

assert(p == &opt_i);

// destuctor
if (opt_constructed) {
  // call opt_i's destructor if it has one
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • `*opt` returns a reference to the internal member or throws an exception if it has not been constructed. `opt=24` assigns to the already-constructed member. – Richard Hodges Oct 21 '15 at 16:16
  • ignore me. wasn't thinking. – NathanOliver Oct 21 '15 at 16:18
  • Can you point the part of the documentation which would back your answer up? – Julien Oct 22 '15 at 06:55
  • See the narrative on semantics. Note that an optional is semantically equivalent to T, plus being able to be uninitialised. http://www.boost.org/doc/libs/1_58_0/libs/optional/doc/html/boost_optional/tutorial/design_overview/the_semantics.html – Richard Hodges Oct 22 '15 at 08:00