std :: variant和boost :: variant之间有什么区别? [英] What are the differences between std::variant and boost::variant?
问题描述
在此问题的答案中:
C ++标准库中的boost :: variant等效于什么?
有人提到 boost :: variant
和 std :: variant
有所不同。
- 就使用这些类的人而言,有什么区别?
- 有什么动机委员会是否表示采用具有这些差异的
std :: variant
? - 使用这两个代码进行编码时应注意什么? ,以保持与切换到另一个的最大兼容性?
(动机是使用 boost :: variant
在C ++ 17之前的代码中)
-
分配/安置行为:
-
boost :: variant
可能< a href = http://www.boost.org/doc/libs/1_62_0/doc/html/variant/design.html#variant.design.never-empty.heap-backup-solution rel = noreferrer>在执行赋值时将其分配给实时的变量
。有 a控制何时发生的规则数量,因此boost :: variant
是否分配内存取决于Ts
实例化。 -
std :: variant
将从不动态分配内存。但是,作为对C ++对象复杂规则的让步,如果抛出分配/放置,则变体
可以进入 valueless_by_exception状态。在这种状态下,不能访问变体
,也不能访问用于访问特定成员作品的任何其他功能。
只有在分配/安置抛出时,您才能进入此状态。
-
-
升压。变体包括
recursive_variant
,其中允许变体
包含自身。实际上,它们是指向boost :: variant
的指针的特殊包装,但它们与访问机制绑定在一起。
std :: variant
没有此类帮助程序类型。 -
std :: variant
提供了更多使用C ++ 11后功能的功能。例如:
-
它将转发特殊成员的
noexcept
状态 -
它具有基于可变参数模板的就地构造函数和放置功能。</ p>
-
缺陷解决方案应用于C ++ 17可能意味着它还将转发其类型的普通可复制性。也就是说,如果所有类型都是微不足道的,那么
variant< Ts>
也是如此。
-
In an answer to this SO question:
What is the equivalent of boost::variant in the C++ standard library?
it is mentioned that boost::variant
and std::variant
differ somewhat.
- What are the differences, as far as someone using these classes is concerned?
- What motivation did the committee express to adopt
std::variant
with these differences? - What should I watch out for when coding with either of these, to maintain maximum compatibility with switching to the other one?
(the motivation is using boost::variant
in pre-C++17 code)
Assignment/emplacement behavior:
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
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 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
has no such helper type.std::variant
offers more use of post-C++11 features. For example:It forwards the
noexcept
status of the special member functions of its constituent types.It has variadic template-based in-place constructors and emplacement functions.
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屋!