Search code examples
c++boost-optional

Need clarification on boost::optional type


I’m trying to make sense out of a few details obtained from the core file with respect to boost::optional type variable.

Variable:

boost::optional<Cacher> cacher_;

Frame #5 from the core:

(gdb) p this->cacher_
$1 = boost::optional

The line being executed in this frame is:

cacher_ = boost::none;

As a result, a few frames leading upto to the crash, point to boost library code:

#1  0x000000000152f96c in destroy_impl (this=0x32557590) at /opt/include/boost/optional/optional.hpp:479
#2  destroy (this=0x32557590) at /opt/include/boost/optional/optional.hpp:439
#3  assign (this=0x32557590) at /opt/include/boost/optional/optional.hpp:313
#4  operator= (none_=NULL, this=0x32557590) at /opt/include/boost/optional/optional.hpp:615

Frame #0 is where the destructor of Cacher is called, and the crash is because the memory held by the object has already been freed.

My question:

  1. Does boost::optional indicate that the memory held by cacher_ is valid?
  2. As a result of assigning boost::none to cacher_, would the object be destroyed?

Apologies if the details to diagnose the problem are insufficient. I’ll try to provide additional details based on the responses.

Thanks!


Solution

  • Yes, boost::optional keeps track of whether it holds a valid object. This can be checked by using operator bool() or is_initialized().

    If you assign boost::none (or call .reset()) it will properly destroy the object it holds, if any.

    The same holds true for std::optional (except for boost::none assignment, to the best of my knowledge).