std::optional in C++
In this article, we will discuss the std::optional in C++ with several examples.
What is std::optional?
The template class std::optional contains an optional value, which may or may not have a legitimate deal. It improves the code readability to eliminate the need for null pointers. It provides a standardized way to represent optional values.
Why was it added to C++?
The std::optional feature in C++ addressed the several issues with null pointers, including:
- Safety: Null pointers may result in errors or other unforeseen actions. Code is safer because "std::optional" prevents null pointer dereferences.
- Expression: Null pointers have a few words. It can be challenging to determine from the appearance of a null pointer whether it denotes a missing value, an error, or something else. By allowing developers to explicitly indicate the potential for absence, "std::optional" enhances the expressiveness and self-documentation of code.
- Readability: Null pointer-using code can be challenging to read and comprehend. Code is easier to read because optional values are represented clearly and concisely by "std::optional".
Using std::optional:
A variable of type std::optional<T> must first be declared, where T denotes the type of the optional value. For instance:
std::optional<int> my_optional_int;
- After that, you can use the operator=() to give the optional variable a value:
my_optional_int = 10;
- You can utilize the has_value() member function to determine whether the optional variable has a value:
if (my_optional_int.has_value()) {
// The optional variable contains a value.
}my_optional_int = 10;
- Use the value() function of a member to get access to the optional variable's value. It is crucial to remember that the value() member function will raise an error if the optional variable is empty:
int my_int = my_optional_int.value();
- Use the value_or() member function to access the optional variable's value securely. If the optional variable is empty, the value_or() member function, which accepts a default value as a parameter, returns the default value:
int my_int = my_optional_int.value_or(0);
Example:
Let us take an example that demonstrates how to use std::optional to represent a function's return value that might not succeed:
#include <iostream>
#include <optional>
std::optional<int> get_value() {
int value;
std::cout << "Enter a value: ";
if (std::cin >> value) {
return value; // Return the user-provided value.
} else {
return std::nullopt; // Return std::nullopt to indicate failure.
}
}
int main() {
std::optional<int> my_optional_int = get_value();
if (my_optional_int.has_value()) {
int my_int = my_optional_int.value();
std::cout << "Value: " << my_int << std::endl;
} else {
std::cout << "Function failed to provide a value." << std::endl;
}
return 0;
}
Output:
Explanation:
- In this example, the new value will be substituted for the existing one if the optional variable already has one.
- After that, the std::nullopt being used to signify a lack of value.
- Use the operator=() operator and std::nullopt as the argument to assign std::nullopt to a std::optional variable to represent a lack of value. For instance: std::optional std::nullopt; my_optional_int; my_optional_int;
- A std::optional variable will be empty after receiving the value std::nullopt.
Example:
Let us take an example to demonstrate how to give values to std::optional variables and assign std::nullopt to indicate a variable with no weights.
#include <iostream>
#include <optional>
int main() {
// Assign the value 10 to the optional variable.
std::optional<int> my_optional_int;
my_optional_int = 11;
// Check if the optional variable contains a value.
if (my_optional_int.has_value()) {
// The optional variable contains a value.
int my_int = my_optional_int.value();
std::cout << "my_optional_int contains a value: " << my_int << std::endl;
} else {
// The optional variable does not contain a value.
std::cout << "my_optional_int does not contain a value." << std::endl;
}
// Assign std::nullopt to the optional variable to represent a lack of value.
my_optional_int = std::nullopt;
// Check if the optional variable contains a value.
if (my_optional_int.has_value()) {
// The optional variable does not contain a value.
} else {
// The optional variable contains a lack of value.
std::cout << "my_optional_int contains a lack of value." << std::endl;
}
return 0;
}
Output:
Checking if a value is present:
To determine whether a value is present in an std::optional variable:Using has_value():
If the optional variable has a value, the has_value() member function returns true; otherwise, it returns false.
Example:
#include <iostream>
#include <optional>
#include <string>
int main() {
std::optional<int> my_optional_int;
// Prompt the user to enter an integer value (or 'n' for no value).
std::cout << "Enter an integer value (or 'n' for no value): ";
std::string userInput;
std::cin >> userInput;
if (userInput == "n") {
my_optional_int = std::nullopt;
} else {
try {
int value = std::stoi(userInput);
my_optional_int = value;
} catch (const std::invalid_argument& e) {
std::cout << "Invalid input. Not an integer." << std::endl;
return 1;
}
}
// Check if the optional variable contains a value.
if (my_optional_int.has_value()) {
std::cout << "The optional variable contains a value: " << my_optional_int.value() << std::endl;
} else {
std::cout << "The optional variable does not contain a value." << std::endl;
}
return 0;
}
Output:
Using the bool() operator
It is possible to convert std::optional variables to bool implicitly. You don't need to explicitly call the has_value() member function when using the if statement to determine whether an optional variable has a value. For instance:
std::optional my_optional_int;
if (my_optional_int) {
// The optional variable contains a value.
} else {
// The optional variable does not contain a value.
}
What approach should you take?
It is typically advised to use the has_value() member function to determine whether an optional variable has a value. It is due to how much more precise and more straightforward to read and understand the has_value() member function is.
However, the implicit conversion to bool may be more practical in some circumstances. For example, the has_value() member function might not be available, if an expression contains an optional variable. Use the implicit conversion to bool to determine whether the optional variable has a value in these circumstances.
Accessing the value:
The value of a std::optional can be accessed in one of two ways:
Using value():
If the optional variable has a value, the value() member function returns that value. The value() member function will raise an exception if the optional variable is empty.
For example:
std::optional<int> my_optional_int = 10;
// Access the value of the optional variable.
int my_int = my_optional_int.value();
The following code will raise an exception if the optional variable is empty:
std::optional<int> my_optional_int;
// Access the value of the optional variable.
int my_int = my_optional_int.value();
Using value_or():
If the optional variable has a value, the value_or() member function returns that value. The value_or() member function will return the default value, provided as an argument if the optional variable is empty.
For example:
std::optional<int> my_optional_int;
// Access the value of the optional variable, or return 0 if the variable does not contain a value.
int my_int = my_optional_int.value_or(0);
The value_or() member function is a secure way to access an optional variable's value because it won't raise an exception if the optional variable is empty.
Accessing the value without checking for its presence using value():
It is typically advisable to utilize the value_or() member function to acquire the value of an optional variable, as it provides enhanced security.
However, there are some circumstances in which using the value() member function without first checking for the presence of a deal may be necessary. For instance, you might need to use the value() member function without checking if a value is present if you are composing a part that expects an optional variable as an argument.
The optional variable needs to be guaranteed to have a value before you use the value() member function without first checking for value presence. If not, your code might raise an error.
Using value_or() to provide a default value when the value is absent:
When an optional variable's value is missing, it can be helpful to provide a default value using the value_or() member function. It is beneficial in several circumstances. For instance, when returning the outcome of a process that produces an optional variable, you can use the value_or() member function to provide a default value.
Common use cases:
There are several use cases of the std::optional in C++. Some main use cases of the std::optional in C++ are as follows:
Handling optional function return values:
The handling of optional function return values is one typical application of std::optional. For instance, a function that tries to convert a string into a number might return a std::optional<int>. Due to this, an exception need not be raised for the function to indicate that the string could not be parsed.
Example:
#include <iostream>
#include <optional>
#include <string>
std::optional<int> parse_int(const std::string& str) {
try {
// Try to parse the string into an integer.
int value = std::stoi(str);
// The string was parsed successfully.
return value;
} catch (const std::invalid_argument& e) {
// The string could not be parsed.
return std::nullopt;
}
}
int main() {
// Prompt the user to enter a string that represents an integer.
std::cout << "Enter a string that represents an integer: ";
std::string userInput;
std::cin >> userInput;
// Call the parse_int function to parse the input string.
std::optional<int> result = parse_int(userInput);
// Check if the optional variable contains a value.
if (result.has_value()) {
std::cout << "Parsed integer: " << result.value() << std::endl;
} else {
std::cout << "Input string is not a valid integer." << std::endl;
}
return 0;
}
Output:
Dealing with optional configuration settings:
Dealing with optional configuration settings is another typical application for std::optional. A program might have a configuration option that enables the user to enter the location of a log file. This configuration option may be optional, where the program can still function without a log file.
Example:
#include <iostream>
#include <optional>
#include <string>
#include <fstream>
// Function to read the log file path from the configuration file.
bool read_config_value(const std::string& key, std::string& value) {
// Simulated implementation for reading the configuration file.
// Replace this with your actual code to read the configuration.
if (key == "log_file_path") {
value = "my_custom_log.log"; // Simulated configuration value.
return true;
}
return false; // Simulated failure case.
}
int main() {
std::optional<std::string> log_file_path;
// Read the log file path from the configuration file.
std::string config_value;
if (read_config_value("log_file_path", config_value)) {
log_file_path = config_value;
}
// If the log file path is not specified, use the default log file path.
if (!log_file_path.has_value()) {
log_file_path = "/var/log/my_program.log";
}
// Output the selected log file path.
if (log_file_path.has_value()) {
std::cout << "Log file path: " << log_file_path.value() << std::endl;
} else {
std::cout << "Log file path not specified, using the default." << std::endl;
}
return 0;
}
Output:
Safely representing nullable objects:
Nullable objects can also be represented securely using std::optional. A program might have a database table with a column for a user's email address. The email address column might be nullable, meaning only some users will have a value in it.
The use of std::optional for representing a nullable object safely in code is demonstrated in the following example:
#include <iostream>
#include <optional>
#include <string>
struct User {
std::optional<std::string> email;
};
int main() {
// Create a new user object.
User user;
// Set the user's email address.
user.email = "[email protected]";
// Check if the user has an email address.
if (user.email.has_value()) {
// The user has an email address.
std::string email = user.email.value();
std::cout << "User's email address: " << email << std::endl;
} else {
// The user does not have an email address.
std::cout << "User does not have an email address." << std::endl;
}
return 0;
}
Output:
Explanation:
Nullable objects can be represented using the std::optional type to avoid errors like null pointer dereferences.
Exception safety:
The term "exception safety" describes a program's capacity to manage exceptions in a controlled and predictable manner. When an exception is thrown, an exception-safe program won't crash or corrupt its state.
How exception safety is provided by std::optional:
The std::optional provides various mechanisms for offering exception safety. Firstly, it safeguards against dereferencing null pointers. Given that std::optional variables can never be null, this protection holds true.
Second, std::optional offers a secure access to an optional variable's value. If the optional variable is empty, the value_or() member function returns a default value. Otherwise, it returns the value of the optional variable. It means that you never have to worry about throwing an exception when accessing the value of an optional variable.
Third, function return values can be safely represented using std::optional. Since std::optional functions cannot return null, this holds true.
#include <iostream>
#include <optional>
#include <string>
#include <sstream>
std::optional<int> parse_int(const std::string& str) {
int value;
std::istringstream ss(str);
if (ss >> value) {
// The string was parsed successfully.
return value;
} else {
// The string could not be parsed.
return std::nullopt;
}
}
int main() {
// Try to parse the string "10" into an integer.
std::optional<int> value = parse_int("19");
// If the string was parsed successfully, print the value.
if (value.has_value()) {
std::cout << value.value() << std::endl;
} else {
// The string could not be parsed.
std::cerr << "The string could not be parsed." << std::endl;
}
return 0;
}
Output:
Output:
Using std::optional to handle the scenario where the string cannot be parsed ensures exception safety in this code.The std::nullopt will be returned by the parse_int() function if the string could not be parsed. After that, the value is printed by the main() function after determining whether the value variable has a value. If the string cannot be parsed, it stops the code from throwing an exception.