问题描述
在这个 SO 问题的答案中:
In an answer to this SO question:
C++ 标准库中 boost::variant 的等价物是什么?
提到boost::variant
和std::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 livevariant
. There are a number of rules that govern when this can happen, so whether aboost::variant
will allocate memory depends on theTs
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 thevariant
may enter the "valueless_by_exception" state. In this state, thevariant
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 avariant
to contain itself. They're essentially special wrappers around a pointer to aboost::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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!