在这个 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 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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!