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

查看:220
本文介绍了std :: variant和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后功能的功能。例如:





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 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 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 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 has no such helper type.

  • std::variant offers more use of post-C++11 features. For example:

这篇关于std :: variant和boost :: variant之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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