Guy Sirton
Guy Sirton

Reputation: 8401

How to set a boost::optional back to an uninitialized state?

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
}

Upvotes: 58

Views: 35809

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

x = boost::none;

Upvotes: 113

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

One simple way is this:

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

Or simply:

x.reset(); 

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

Upvotes: 15

Related Questions