std::variant 和 boost::variant 有什么区别?

编程入门 行业动态 更新时间:2024-10-11 01:10:20
本文介绍了std::variant 和 boost::variant 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在这个 SO 问题的答案中:

In an answer to this SO question:

C++ 标准库中 boost::variant 的等价物是什么?

提到boost::variantstd::variant有些不同.

就使用这些类的人而言,有什么区别?委员会表示采用具有这些差异的 std::variant 的动机是什么?使用其中任何一个进行编码时我应该注意什么,以保持切换到另一个的最大兼容性?

(动机是在 C++17 之前的代码中使用 boost::variant)

(the motivation is using boost::variant in pre-C++17 code)

推荐答案

分配/安置行为:

Assignment/emplacement behavior:

boost::variant 可以在执行赋值时分配内存到实时variant.有 a控制何时发生这种情况的规则数量,所以 boost::variant 是否会分配内存取决于它被实例化的 Ts.

boost::variant may allocate memory when performing assignment into a live variant. There are a number of rules that govern when this can happen, so whether a boost::variant will allocate memory depends on the Ts it is instantiated with.

std::variant永远动态分配内存.但是,作为对 C++ 对象复杂规则的让步,如果赋值/定位抛出,则 variant 可能 进入valueless_by_exception"状态.在这种状态下,不能访问 variant,也不能访问任何其他访问特定成员的函数.

std::variant will never dynamically allocate memory. However, as a concession to the complex rules of C++ objects, if an assignment/emplacement throws, then the variant may enter the "valueless_by_exception" state. In this state, the variant cannot be visited, nor will any of the other functions for accessing a specific member work.

您只能在分配/安置抛出时进入此状态.

You can only enter this state if assignment/emplacement throws.

Boost.Variant 包括 recursive_variant,其中 允许 variant 包含自身.它们本质上是对 boost::variant 指针的特殊包装,但它们与访问机制相关联.

Boost.Variant includes recursive_variant, which allows a variant to contain itself. They're essentially special wrappers around a pointer to a boost::variant, but they are tied into the visitation machinery.

std::variant 没有这样的辅助类型.

std::variant has no such helper type.

std::variant 提供了对 C++11 后特性的更多使用.例如:

std::variant offers more use of post-C++11 features. For example:

它转发其组成类型的特殊成员函数的noexcept状态.

它具有基于可变参数模板的就地构造函数和定位函数.

It has variadic template-based in-place constructors and emplacement functions.

缺陷解决方案 应用于 C++17 可能意味着它也将转发其类型的微不足道的可复制性.也就是说,如果所有类型都可以简单地复制,那么 variant 也是如此.

Defect resolutions applied to C++17 may mean that it will also forward trivial copyability of its types. That is, if all of the types are trivially copyable, then so too will variant<Ts>.

这篇关于std::variant 和 boost::variant 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 08:51:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/826327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   std   variant   boost

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!