Using optionals to represent the failure of a function

suggest change

Before C++17, a function typically represented failure in one of several ways:

* e.g. Calling a function `Delegate *App::get_delegate()` on an `App` instance that did not have a delegate would return `nullptr`.
* This is a good solution for objects that have been dynamically allocated or are large and managed by pointers, but isn't a good solution for small objects that are typically stack-allocated and passed by copying.

In this example, John is given two pets, Fluffy and Furball. The function Person::pet_with_name() is then called to retrieve John’s pet Whiskers. Since John does not have a pet named Whiskers, the function fails and std::nullopt is returned instead.

#include <iostream>
#include <optional>
#include <string>
#include <vector>

struct Animal {
    std::string name;
};

struct Person {
    std::string name;
    std::vector<Animal> pets;
    
    std::optional<Animal> pet_with_name(const std::string &name) {
        for (const Animal &pet : pets) {
            if (pet.name == name) {
                return pet;
            }
        }
        return std::nullopt;
    }
};

int main() {
    Person john;
    john.name = "John";
    
    Animal fluffy;
    fluffy.name = "Fluffy";
    john.pets.push_back(fluffy);
    
    Animal furball;
    furball.name = "Furball";
    john.pets.push_back(furball);
    
    std::optional<Animal> whiskers = john.pet_with_name("Whiskers");
    if (whiskers) {
        std::cout << "John has a pet named Whiskers." << std::endl;
    } else {
        std::cout << "Whiskers must not belong to John." << std::endl;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::optional:
* Using optionals to represent the failure of a function

Table Of Contents
8 Arrays
11 Loops
31 std::optional
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype