在 answer 中对于这个 SO 问题:
What is the equivalent of boost::variant in the C++ standard library?
提到boost::variant
和std::variant
有些不同。
- 就使用这些类的人而言,有什么区别?
- 委员会表示采用具有这些差异的
std::variant
的动机是什么? - 在使用其中任何一种编码时我应该注意什么,以保持与切换到另一种的最大兼容性?
(动机是在 C++17 之前的代码中使用 boost::variant
)
最佳答案
分配/就位行为:
boost::variant
可能allocate memory when performing assignment进直播variant
.有a number of rules that govern when this can happen , 所以是否是boost::variant
将分配内存取决于Ts
它被实例化了。std::variant
从不动态分配内存。然而,作为对 C++ 对象的复杂规则的让步,如果赋值/放置抛出,那么variant
可能进入“valueless_by_exception”状态。在这种状态下,variant
无法访问,访问特定成员的任何其他功能也无法使用。只有在分配/安置抛出时才能进入此状态。
Boost.Variant 包括
recursive_variant
, 其中 allows avariant
to contain itself .它们本质上是指向boost::variant
的指针的特殊包装。 ,但它们与访问机制相关联。std::variant
没有这样的辅助类型。std::variant
提供更多后 C++11 特性的使用。例如:它转发
noexcept
其组成类型的特殊成员函数的状态。它具有基于可变参数模板的就地构造函数和就地函数。
缺陷解决方案applied to C++17 may mean that it will also forward trivial copyability of its types .也就是说,如果所有类型都可以轻松复制,那么
variant<Ts>
也可以复制。 .
关于c++ - std::variant 和 boost::variant 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40201371/