58

How can I "reset"/"unset" a boost::optional?

optional<int> x;

if( x )
{
  // We won't hit this since x is uninitialized
}
x = 3;
if( x )
{
  // Now we will hit this since x has been initialized
}
// What should I do here to bring x back to uninitialized state?
if( x )
{
  // I don't want to hit this
}
manlio
  • 18,345
  • 14
  • 76
  • 126
Guy Sirton
  • 8,331
  • 2
  • 26
  • 36
  • 3
    It is a little bit of a mystery to me why there is no `optional::clear` or `optional::empty`. – pmr Jan 22 '12 at 01:56
  • 1
    Probably because there completely does not need to be one. – Lightness Races in Orbit Jan 22 '12 at 01:57
  • 1
    @LightnessRacesinOrbit: Can you elaborate? I'm looking at this in the context of optional member variables where you want to essentially reset some of the state of an object. Perhaps there's a better way of doing that. – Guy Sirton Jan 22 '12 at 02:04
  • @Guy: Instead, please explain (for pmr) why there needs to be an `optional::clear` or `optional::empty`. – Lightness Races in Orbit Jan 22 '12 at 03:48
  • 2
    @LightnessRacesinOrbit: I didn't say there needs to be one :-) but I'll have a go, we have vector::clear and shared_ptr::reset so why is optional::clear or optional::reset different? Are you saying that optional shouldn't be reset or are you asying that the assignment idiom is all one needs or are you saying there should only be one way of doing something? I'm not arguing - just interested in your thoughts... – Guy Sirton Jan 22 '12 at 23:10
  • @GuySirton: pmr asked, and I answered! There is no need for the solutions pmr asked for, because the other solutions in this answer exist. – Lightness Races in Orbit Jan 22 '12 at 23:55
  • See also [How to disengage std::experimental::optional](http://stackoverflow.com/questions/26897066/how-to-disengage-stdexperimentaloptional) – M.M Dec 22 '15 at 06:15

2 Answers2

113
x = boost::none;

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
15

One simple way is this:

x = optional<int>(); //reset to default

Or simply:

x.reset(); 

It destroys the current value, leaving this uninitialized (default).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 16
    [`reset()` is deprecated](http://www.boost.org/doc/libs/1_44_0/libs/optional/doc/html/boost_optional/synopsis.html) – johnsyweb Jan 22 '12 at 02:05
  • 2
    Here's [a more specific link](http://www.boost.org/doc/libs/1_48_0/libs/optional/doc/html/boost_optional/detailed_semantics.html#reference_optional_reset). Basically, Benjamin's answer is the new `.reset();`. – Xeo Jan 22 '12 at 02:40
  • 3
    `optional::reset();` is simple to use right and difficult to use wrong, so why deprecate it? (citation to a famous guideline by Scott Meyers) – fiorentinoing Apr 13 '18 at 15:47