Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ optional::reset() Function



The std::optional::reset() function in C++, is used to clear the current state of the optional object, making it empty by destroying the any contained value. If the optional previously held a value, the destructor of that value is called.

When this function is invoked, the optional object no longer contains a value, and the has_value() function will return false.

Syntax

Following is the syntax for std::optional::reset() function.

void reset() noexcept;

Example 1

Let's look at the following example, where we are going to clear the optional value.

#include <iostream>
#include <optional>
int main() {
   std::optional < int > x = 11121;
   std::cout << "Initial value: " << * x << std::endl;
   x.reset();
   if (!x.has_value()) {
      std::cout << "It Is Empty Now." << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Initial value: 11121
It Is Empty Now.

Example 2

Consider the following example, where we are going to use the reset() to clear the value of the optional. Later, we are assigning the new value and observing the output.

#include <iostream>
#include <optional>
int main() {
   std::optional < std::string > x = "Hello Everyone";
   std::cout << "Before reset: " << * x << std::endl;
   x.reset();
   if (!x.has_value()) {
      std::cout << "Now It Is Empty." << std::endl;
   }
   x = "Welcome Back.!";
   std::cout << "After reassign : " << * x << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Before reset: Hello Everyone
Now It Is Empty.
After reassign : Welcome Back.!
cpp_optional.htm
Advertisements