std::variant 和 boost::variant 有什么区别? [英] What are the differences between std::variant and boost::variant?

查看:27
本文介绍了std::variant 和 boost::variant 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个 SO 问题的答案中:

In an answer to this SO question:

C++ 标准库中 boost::variant 的等价物是什么?

提到boost::variantstd::variant有些不同.

  • 就使用这些类的人而言,有什么区别?
  • 委员会表示采用具有这些差异的 std::variant 的动机是什么?
  • 使用其中任何一个进行编码时我应该注意什么,以保持切换到另一个的最大兼容性?

(动机是在 C++17 之前的代码中使用 boost::variant)

(the motivation is using boost::variant in pre-C++17 code)

推荐答案

  • 分配/安置行为:

    • Assignment/emplacement behavior:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆