How to use std::optional in Modern C++

🗞️ It is useful for situations where you want to indicate the absence of a value in a clearer and safer way than using null pointers.


How to use std::optional in Modern C++


std::optional is a functionality introduced in the C++17 standard library that encapsulates an optional value, that is, a value that can or cannot be present.

It is useful for situations where you want to indicate the absence of a value in a clearer and safer way than using null pointers or special values.

Let’s see some examples of use!


01. Creation and basic use

#include <iostream>
#include <optional>

std::optional<int> find_even_number(int num) {
    if (num % 2 == 0) {
        return num;
    } else {
        return std::nullopt; // Indicates absence of value
    }
}

int main() {
    int num = 4;
    auto result = find_even_number(num);

    if (result) {
        std::cout << "Even number found: " << result.value() << '\n';
    } else {
        std::cout << "Number is not even.\n";
    }

    return 0;
}

02. Using std::optional with std::string

#include <iostream>
#include <optional>

std::optional<std::string> get_middle_name(const std::string& full_name) {
    size_t space1 = full_name.find(' ');
    if (space1 == std::string::npos) {
        return std::nullopt;
    }
    size_t space2 = full_name.find(' ', space1 + 1);
    if (space2 == std::string::npos) {
        return std::nullopt;
    }
    return full_name.substr(space1 + 1, space2 - space1 - 1);
}

int main() {
    std::string name = "Marcos Simoes Oliveira";
    auto middle_name = get_middle_name(name);

    if (middle_name) {
        std::cout << "Middle name: " << *middle_name << '\n';
    } else {
        std::cout << "Middle name was not found.\n";
    }

    return 0;
}


03. Handling std::optional

#include <iostream>
#include <optional>

int main() {
    std::optional<int> opt;

    // Assigning a value
    opt = 42;
    std::cout << "Value: " << *opt << '\n';

    // Removing the value
    opt.reset();
    if (!opt) {
        std::cout << "No value.\n";
    }

    // Using default value
    std::cout << "Value or pattern: " << opt.value_or(-1) << '\n';

    return 0;
}

04. Working with functions that return std::optional

#include <iostream>
#include <optional>

std::optional<std::string> get_first_word(const std::string& sentence) {
    size_t pos = sentence.find(' ');
    if (pos == std::string::npos) {
        return std::nullopt;
    }
    return sentence.substr(0, pos);
}

int main() {
    std::string sentence = "Hello, World!";
    auto first_word = get_first_word(sentence);

    if (first_word) {
        std::cout << "First word: " << *first_word << '\n';
    } else {
        std::cout << "The first word was not found.\n";
    }

    return 0;
}

In summary, std::optional is an elegant and safe way to handle optional values in C++, providing a clearer and less error-prone alternative compared to using null pointers or special values.



cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles