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

C++BoostBoost Optional

C++ Problem Overview


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
}

C++ Solutions


Solution 1 - C++

x = boost::none;

Solution 2 - C++

One simple way is this:

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

Or simply:

x.reset(); 

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuy SirtonView Question on Stackoverflow
Solution 1 - C++Benjamin LindleyView Answer on Stackoverflow
Solution 2 - C++NawazView Answer on Stackoverflow