c++ - std::variant 和 boost::variant 有什么区别?

标签 c++ boost c++17 variant boost-variant

answer 中对于这个 SO 问题:

What is the equivalent of boost::variant in the C++ standard library?

提到boost::variantstd::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 a variant to contain itself .它们本质上是指向 boost::variant 的指针的特殊包装。 ,但它们与访问机制相关联。

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

  • std::variant提供更多后 C++11 特性的使用。例如:

关于c++ - std::variant 和 boost::variant 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40201371/

相关文章:

c++ - 运行时检查失败#2-变量 'sortObject'周围的堆栈已损坏。怎么修?

c++ - 用 Boost::Test 模拟

c++ - 通过 http 代理 boost asio ssl 身份验证

c++ - View 和跨步 View 的函数模板特化和 const 噩梦

c++ - 如何创建轮廓

c++ - while (cin >> *pchar) 在 Ctrl-Z 之后等待进一步输入

c++ - 标准库 `emplace` 函数是否使用 `std::in_place` 标签

c++ - 模板推导指南可以调用 constexpr 函数吗?

c++ - 在 C++ 中将图像从 Pylon 转换为 Opencv

c++ - boost::serialization 中的派生类偏移量计算。有效吗?