类模板 std::optional 管理一个可选的所含值,即既可以存在也可以不存在的值。 一种常见的 optional 使用情况是作为可能失败的函数的返回值。与如 std::pair<T, bool> 等其他手段相比,optional 可以很好地处理构造开销高昂的对象,并更加可读,因为它明确表达了意图。
#include <optional> #include <print> #include <vector> int main() { constexpr std::optional<int> none{std::nullopt}; constexpr std::optional<int> some{42}; static_assert(none.begin() == none.end()); static_assert(some.begin() != some.end()); // 支持范围 for 循环 for (int ...
optional cppreference.com Create account Page Discussion Standard revision:DiffC++98/03C++11C++14C++17C++20C++23C++26 View Edit History std::optional<T>::optional constexproptional()noexcept; (1)(since C++17) constexproptional(std::nullopt_t)noexcept;...
总的来说,不建议将实体中的每个字段都用 std::optional 包装。这可能会导致以下问题:代码臃肿: 过度...
A reference to the new contained value. Exceptions Any exception thrown by the selected constructor ofT. If an exception is thrown,*thisdoes not contain a value after this call (the previously contained value, if any, had been destroyed). ...
对于 C++ 的std::optional来说,目前不支持这种机制,所以存储空间方面永远是有开销的。也可以考虑使用非...
首先,考虑内存开销。cppstd::optional每个实例在内存中占用的大小取决于其内部存储的类型。例如,当内部存储为int类型时,cppstd::optional实例将额外占用存储bool值的空间来判断该值是否为非空。不过,这种额外开销在大多数情况下是可以接受的,因为相对于避免空指针异常所带来的收益,它显得微不足道。其...
cppreference.com Créer un compte Page Discussion Lire Modifier Historique C++ reference C++98, C++03, C++11, C++14, C++17, C++20 Support des compilateurs Implémentations autonomes Language Concepts de base Mots-clefs du C++ Préprocesseur Expressions Déclaration Initialisation Fonctions Instructions ...
A non-owning reference to a string. Useful for providing an abstraction on top of strings (e.g. for parsing). // Regular strings. std::string_view cppstr{ "foo" }; // Wide strings. std::wstring_view wcstr_v{ L"baz" }; // Character arrays. char array[3] = {'b', 'a', ...
std::any x {5}; x.has_value() // == true std::any_cast<int>(x) // == 5 std::any_cast<int&>(x) = 10; std::any_cast<int>(x) // == 10 std::string_view A non-owning reference to a string. Useful for providing an abstraction on top of strings (e.g. for parsing)...