std::variant<Types...>::valueless_by_exception
来自 cppreference.cn
constexpr bool valueless_by_exception() const noexcept; |
(自 C++17 起) | |
返回 false 仅当且仅当 variant 存储了一个值时。
[编辑] 注解
当在以下情况中初始化所含值时,variant 可能变为无值状态
由于 variant 永远不允许分配动态内存,因此在这些情况下,无法保留和恢复先前的值。“可选”情况可以避免抛出异常,如果该类型提供非抛出移动,并且实现首先在栈上构造新值,然后将其移动到 variant 中。
这甚至适用于非类类型的 variant
struct S { operator int() { throw 42; } }; std::variant<float, int> v{12.f}; // OK v.emplace<1>(S()); // v may be valueless
因异常而无值的 variant —— 即,由于先前从上面列出的情况之一引发的异常而没有值 —— 被视为处于无效状态
-
index
返回variant_npos
-
get
抛出bad_variant_access
-
visit
和 成员-visit
(自 C++26 起) 抛出bad_variant_access
[编辑] 示例
运行此代码
#include <cassert> #include <iostream> #include <stdexcept> #include <string> #include <variant> struct Demo { Demo(int) {} Demo(const Demo&) { throw std::domain_error("copy ctor"); } Demo& operator= (const Demo&) = default; }; int main() { std::variant<std::string, Demo> var{"str"}; assert(var.index() == 0); assert(std::get<0>(var) == "str"); assert(var.valueless_by_exception() == false); try { var = Demo{555}; } catch (const std::domain_error& ex) { std::cout << "1) Exception: " << ex.what() << '\n'; } assert(var.index() == std::variant_npos); assert(var.valueless_by_exception() == true); // Now the var is "valueless" which is an invalid state caused // by an exception raised in the process of type-changing assignment. try { std::get<1>(var); } catch (const std::bad_variant_access& ex) { std::cout << "2) Exception: " << ex.what() << '\n'; } var = "str2"; assert(var.index() == 0); assert(std::get<0>(var) == "str2"); assert(var.valueless_by_exception() == false); }
可能的输出
1) Exception: copy ctor 2) Exception: std::get: variant is valueless
[编辑] 参见
(C++17) |
读取 variant 的值,给定索引或类型 (如果类型是唯一的),错误时抛出异常 (函数模板) |
返回 variant 所持有的候选项的从零开始的索引(公共成员函数) | |
(C++17) |
当无效访问 variant 的值时抛出的异常(类) |