我可以安全地指向重新分配的 boost::optional 的数据吗?

Can I safely point to the data of a reassigned boost::optional?

给定以下代码示例:

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

是否可以保证断言始终有效?

是的,这是保证。 boost::optional<T>T 在逻辑上是可选的私有成员。

上面的代码在逻辑上等同于:

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
}