Espaços nominais
Variantes
Ações

std::optional

De cppreference.com

Predefinição:cpp/utility/optional/navbar

<tbody> </tbody>
Definido no cabeçalho <optional>
template< class T > class optional;

A classe genérica std::optional que gerencia o optional contendo o valor, sendo válido ou não.

O uso comum envolvendo o optional é retornar o valor de uma função que provavelmente falhe. Ao contrário de outras abordagens, como std::pair<T,bool>, optional lida bem com objetos de alto custo para construir e ainda é mais legível, pois a intenção é expressa explicitamente.

Qualquer instância do optional<T> a qualquer momento, seja contém um valor ou nã contém valor algum.

If an optional<T> contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined.

When an object of type optional<T> is contextually converted to bool, the conversion returns true if the object contains a value and false if it does not contain a value.

The optional object contains a value in the following conditions:

  • O objeto é inicializável with/assigned from a value of type T or another optional that contains a value.

O objeto não contém o valor perante as devidas condções:

  • The object is default-initialized.
  • The object is initialized with/assigned from a value of type std::nullopt_t or an optional object that does not contain a value.
  • The member function reset() is called.

There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. Alternatively, an optional of a std::reference_wrapper of type T may be used to hold a reference. In addition, a program is ill-formed if it instantiates an optional with the (possibly cv-qualified) tag types std::nullopt_t or std::in_place_t.

Parâmetros de template

T - the type of the value to manage initialization state for. The type must meet the requirements of Destructible (in particular, array types are not allowed).

Tipos dos membros

Member type Definition
value_type T

Funções membros

Predefinição:cpp/utility/optional/dsc constructorPredefinição:cpp/utility/optional/dsc destructorPredefinição:cpp/utility/optional/dsc operator=Predefinição:cpp/utility/optional/dsc operator*Predefinição:cpp/utility/optional/dsc operator boolPredefinição:cpp/utility/optional/dsc valuePredefinição:cpp/utility/optional/dsc value orPredefinição:cpp/utility/optional/dsc swapPredefinição:cpp/utility/optional/dsc resetPredefinição:cpp/utility/optional/dsc emplace
Observadores
Modificadores

Funções não-membros

Predefinição:cpp/utility/optional/dsc operator cmpPredefinição:cpp/utility/optional/dsc make optionalPredefinição:cpp/utility/optional/dsc swap2

Helper classes

Predefinição:cpp/utility/optional/dsc hashPredefinição:cpp/utility/optional/dsc nullopt tPredefinição:cpp/utility/optional/dsc bad optional access

Helpers

Predefinição:cpp/utility/optional/dsc nulloptPredefinição:cpp/utility/optional/dsc in place

Deduction guides

Exemplo

#include <string>
#include <functional>
#include <iostream>
#include <optional>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
    if (b)
        return "Godzilla";
    return {};
}

// std::nullopt can be used to create any (empty) std::optional
auto create2(bool b) {
    return b ? std::optional<std::string>{"Godzilla"} : std::nullopt;
}

// std::reference_wrapper may be used to return a reference
auto create_ref(bool b) {
    static std::string value = "Godzilla";
    return b ? std::optional<std::reference_wrapper<std::string>>{value}
             : std::nullopt;
}

int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';
 
    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create2(true)) {
        std::cout << "create2(true) returned " << *str << '\n';
    }

    if (auto str = create_ref(true)) {
        // using get() to access the reference_wrapper's value
        std::cout << "create_ref(true) returned " << str->get() << '\n';
        str->get() = "Mothra";
        std::cout << "modifying it changed it to " << str->