std::optional
Predefinição:cpp/utility/optional/navbar
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 anotheroptional
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.
Índice |
[editar]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). |
[editar]Tipos dos membros
Member type | Definition |
value_type | T |
[editar]Funções membros
[editar]Funções não-membros
[editar]Helper classes
[editar]Helpers
[editar]Deduction guides
[editar]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::optionalauto create2(bool b){return b ? std::optional<std::string>{"Godzilla"}: std::nullopt;} // std::reference_wrapper may be used to return a referenceauto create_ref(bool b){staticstd::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 ifif(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 valuestd::cout<<"create_ref(true) returned "<< str->get()<<'\n'; str->get()="Mothra";std::cout<<"modifying it changed it to "<< str->get()<<'\n';}}
Saída:
create(false) returned empty create2(true) returned Godzilla create_ref(true) returned Godzilla modifying it changed it to Mothra