Table of contents
1.
Introduction
2.
What is std::optional in C++?
3.
Some Common Member Types and Functions of std::optional
3.1.
value_type
3.2.
reference
3.3.
const_reference
3.4.
has_value()
3.5.
operator* ()
3.6.
operator->()
3.7.
value()
3.8.
value_or()
3.9.
reset()
3.10.
swap()
4.
Example of std::optional in C++
4.1.
Without Using std::optional
4.1.1.
Code
4.2.
C++
4.2.1.
Output
4.2.2.
Code
4.3.
C++
4.3.1.
Output
5.
Disadvantages of std::optional in C++
6.
Frequently Asked Questions
6.1.
What would happen if I tried to access the value of an empty std::optional?
6.2.
How is std::optional different from std::variant?
6.3.
What are the major differences between std::optional and boost::optional?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

std::optional

Author Aayush Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C++ programming language, it can be quite tricky to determine the presence or absence of a value in C++. It can be done with the help of bool variables, but it does not look very readable from the outside. But with the introduction of std::optional in the C++17 standard, it has become much easier. The std::optional can easily indicate the presence and absence of a value without affecting the code clarity.

std::optional

In this blog, we will discuss std::optional in detail. We will study about some major methods of the std::optional class along with code implementations. We will also discuss some drawbacks of using std::optional and some frequently asked questions related to it.

What is std::optional in C++?

The std::optional feature was first introduced in the C++17 Standard Library. It was added to tackle the challenge of representing optional values in a better way in C++. Prior to C++ 17, developers had to manage different indicator values (like 0 indicating false and 1 indicating true) to check the initialization of the value. But with std::optional it can be simply converted to a bool type and returns the required boolean value automatically.

std::optional helps to prevent null-related errors that can occur while dealing with uninitialized values. It increases the code clarity making it easier for other developers to understand the expected behavior of the program. std::functional is used in a variety of situations. Some of these situations are given below.

  • Optional return values in functions.
     
  • Error Handling
     
  • Optional default values of parameters
     
  • Optional configurational parameters
     

These are only a few of the many use cases of std::optional in C++.

Some Common Member Types and Functions of std::optional

std::option has a large number of member functions and types that are available to use with it. We will discuss some of these member types and methods in this section.

value_type

The value_type is a member type of the std::optional class. Itindicates the type of the value that the std::optional can hold.

reference

The reference variable is also a member type of the std::optional class. The "reference" represents a reference pointer to the stored value.

const_reference

Similar to the "reference" pointer it also a member type of the std::optional class. It represents a const reference pointer to the stored value.

has_value()

The has_value() method checks if the std::optional is holding a value.

operator* ()

The operator()* returns a reference to the value in the container.

operator->()

The opeartor->() method allows direct access to the member functions and properties of the value in the container.

value()

It returns the value present in the std::optional container. It throws an exception if the container is empty.

value_or()

The value_or() method works similar to the value() method but it returns a default value if the container is empty.

reset()

The reset() function resets the value present in the std::optional to a state of no value.

swap()

The swap() method is used to swap the values present in two different std::optional instances.

 

These are just some of the few methods and types present in the std::optional() function.

Example of std::optional in C++

In this section, we will look at the usage of std::optional in C++ with the help of some code examples. We will write a simple program just to check if the value present in our std::optional program is null or not.

First, let us look at a program to achieve the desired result without using std::optional.

Without Using std::optional

Code

  • C++

C++

#include <iostream>
using namespace std;

// helper function
int helper (bool flag) {
if (flag) {
return 1;
}
else {
return -1;
}
}

int main () {
int val = helper(true);
if(val != -1){
cout<<val<<endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

output

Now, we will try to get the same functionality as the above code but with the help of std::optional.

Code

  • C++

C++

#include <iostream>
#include <optional>
using namespace std;

// std::optional class
optional <int> helper (bool flag) {
if (flag) {
return 1;
}
else{
return nullopt;
}
}

int main () {
optional <int> val = helper(true);
if(val){
cout<<*val<<endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Output

We achieved the same functionality in both the codes but std::optional made it easier for use to find if our specified condition was true or not. We don't have to deal with null types like -1, 0, nullptr when we use the std::optional class.

Disadvantages of std::optional in C++

While std::optional helps in reducing ambiguity and increasing the code readability of the program, it also has some drawbacks attached to it.
 

  • Compatibility - std::optional is only available in the 2017 and later versions of C++. Hence, it can not be used in projects using earlier versions of C++.
     
  • Less Usage - Even though std::optional is a very good method to check null values, it is still very less popular and unrecognizable amongst the users of C++.
     
  • Compiler Support - Since it is a fairly new feature introduced in C++ 2017, std::optional may not be supported by all the compilers leading to ambiguous behavior.
     
  • Performance - std::optional takes more memory as compared to simple boolean flag which can be used for the same purpose.

Frequently Asked Questions

What would happen if I tried to access the value of an empty std::optional?

We can use the value() method to access the value of a std::optional. If we try to access the value of an empty std::optional, the value() method will result in an exception.

How is std::optional different from std::variant?

In C++, std::optional is used to represent the presence or absence of a single value (like a boolean variable). On the other hand, std::variant is used to represent one value from a set of multiple values.

What are the major differences between std::optional and boost::optional?

Both std::optional and boost:optional are used to represent optional values. The main difference between them lies in their standardization. While std::optional is part of the Standard C++ library, boost::optional is a component of the Boost C++ library.

Conclusion

In this article, we discussed std::optional. We discussed in detail some member types of std::optional along with some examples of std::optional with suitable code implementations. In the end, we concluded by discussing some drawbacks of using std::optional and some frequently asked questions.

So now that you know about std::optional in C++, you can refer to similar articles.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning!

Live masterclass