如何提升::变体存储引用

How does boost::variant store references?

本文关键字:存储 引用 何提升      更新时间:2023-10-16

以下代码编译并执行"正确的操作":

#include <boost/variant.hpp>
#include <iostream>
int main()
{
  int a = 10;
  boost::variant<int&, float&> x = a;
  a = 20;
  std::cout << boost::get<int&>(x) << "n";
  return 0;
}

boost::变体如何存储引用?根据C++标准,引用的存储方式完全取决于编译器。实际上,boost::variant怎么知道引用占用了多少字节?sizeof(T&) == sizeof(T),所以不能使用sizeof()运算符。现在,我知道引用很可能是作为指针实现的,但在语言中没有保证。当变量存储引用时,get<>和访问是如何工作的一个很好的解释会得到额外的分数:)

您可以将结构字段声明为引用。

struct ref_to_int {
    ref_to_int(int& init)
      : _storage(init) {} // _storage stores the reference.
private:
    int& _storage;
};

你可以使用sizeof(ref_to_int),它是我的x64上的8。该字段存储引用。