std::variant是c++17引入的类型安全联合体,本质区别于union:它运行时记录类型索引、自动管理构造/析构,禁止非法访问;而union无类型跟踪、不调用生命周期函数,易致未定义行为。

std::variant 是什么,和 union 有什么本质区别
std::variant 是 C++17 引入的类型安全联合体,它不是 union 的语法糖,而是完全不同的机制:它在运行时记录当前持有的类型(通过内部索引或 type-erased tag),并禁止非法访问。原始 union 不跟踪类型、不调用构造/析构函数,容易导致未定义行为;而 std::variant 自动管理生命周期,访问前可检查状态。
- 如果你试图用
std::get<int>(v)</int>访问一个实际存着double的std::variant<int double></int>,程序会抛出std::bad_variant_access -
std::variant要求所有备选类型都是可构造、可析构的(不能是抽象类或带删除构造函数的类型) - 它不支持引用类型作为备选项(
std::variant<int></int>非法),但可以用std::reference_wrapper替代
怎么安全地读取 std::variant 中的值
最常用的是 std::visit —— 它强制你覆盖所有可能类型,避免漏处理。比反复用 std::holds_alternative + std::get 更健壮、更易维护。
std::variant<int std::string double> v = 3.14;
std::visit([](const auto& x) {
using T = std::decay_t<decltype>;
if constexpr (std::is_same_v<t int>) {
std::cout ) {
std::cout ) {
std::cout <ul>
<li>使用 <code>std::get<t>(v)</t></code> 前必须确保 <code>v.index() == std::variant_alternative_t<t decltype></t></code> 成立,否则抛异常</li>
<li>
<code>std::get_if<t>(v)</t></code> 返回 <code>T*</code>,空指针表示当前不持有该类型,适合条件分支</li>
<li>
<code>std::holds_alternative<t>(v)</t></code> 是类型检查的首选,但仅作判断,不提供访问</li>
</ul>
<h3>std::variant 的默认构造和初始化陷阱</h3>
<p><code>std::variant</code> 默认构造时,<strong>只对第一个备选类型调用默认构造</strong>。如果首类型不可默认构造(比如 <code>std::variant<:string int></:string></code> 没问题,但 <code>std::variant<nondefaultconstructible int></nondefaultconstructible></code> 编译失败),整个 variant 就无法默认构造。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill2990" title="Full access to all Exchange 2010 EWS functions, should work with other EWS Open Source"><img
src="https://img.php.cn/upload/skill/000/000/081/178943955136525.jpg" alt="Full access to all Exchange 2010 EWS functions, should work with other EWS Open Source" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill2990" title="Full access to all Exchange 2010 EWS functions, should work with other EWS Open Source" class="overflowclass">Full access to all Exchange 2010 EWS functions, should work with other EWS Open Source</a>
<p class="overflowclass">可完全访问 Exchange 2010 EWS,管理邮件、文件夹、附件、日历事件、联系人、任务及外出设置。</p>
</div>
<a rel="nofollow" href="/xiazai/skill2990" title="Full access to all Exchange 2010 EWS functions, should work with other EWS Open Source" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<ul>
<li>初始化时尽量显式指定类型:<code>std::variant<int std::string> v{std::in_place_type<:string>, "hello"}</:string></int></code>
</li>
<li>或用 <code>std::make_variant_alternative</code>(C++20)简化构造</li>
<li>不要依赖<a style="color:#f60; text-decoration:underline;" title="隐式转换" href="https://m.php.cn/zt/77300.html" target="_blank">隐式转换</a>来初始化:<code>std::variant<int double> v = 42;</int></code> 是合法的(转成 <code>int</code>),但 <code>std::variant<:string int> v = "abc";</:string></code> 会失败——字符串字面量不会自动转 <code>std::string</code>,除非加括号或用花括号初始化</li>
</ul>
<h3>性能和内存布局需要注意什么</h3>
<p><code>std::variant</code> 的大小至少等于最大备选类型的大小,再加少量额外空间(通常 1–2 <a style="color:#f60; text-decoration:underline;" title="字节" href="https://m.php.cn/zt/16298.html" target="_blank">字节</a>)存索引。它不共享内存,也不做堆分配 —— 所有内容都在栈上连续布局。</p>
<ul>
<li>如果某个备选类型很大(比如含数百字节的结构体),整个 <code>std::variant</code> 就会变大,影响缓存局部性</li>
<li>移动语义有效:移动一个 <code>std::variant</code> 会移动其内部值(如果该类型支持移动)</li>
<li>
<code>std::monostate</code> 可作为“空状态”占位符,让 variant 支持“未初始化”语义,例如 <code>std::variant<:monostate int std::string></:monostate></code>
</li>
</ul>
<p><code>std::variant</code> 的类型安全不是免费的:每次访问都要查索引、每次赋值都可能触发旧值析构+新值构造。真正在意极致性能且能保证类型切换逻辑绝对可控时,原始 <code>union</code> + 手动生命周期管理仍是可行选择 —— 但绝大多数场景,<code>std::variant</code> 的安全收益远大于那点开销。</p></t></decltype></int>C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










