boost::variant如何存储引用?

14
以下代码编译并完成了“正确的事情”:
#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::variant如何存储引用?根据C++标准,引用的存储完全取决于编译器。实际上,boost::variant如何知道引用占用了多少字节呢?sizeof(T&) == sizeof(T),所以它不能使用sizeof()运算符。现在,我知道引用很可能是使用指针实现的,但是语言没有保证。当变量存储引用时,如何使用get<>和访问工作的良好解释可以获得额外的分数 :)

11
通过将它们包装在一个对象中。 << sizeof(std :: vector <char>&),sizeof(std :: vector <char>),sizeof(T); struct T {std :: vector <char>& r; }; 56、56、8。 - Lightness Races in Orbit
1个回答

7
您可以将结构体字段声明为引用。
struct ref_to_int {
    ref_to_int(int& init)
      : _storage(init) {} // _storage stores the reference.
private:
    int& _storage;
};

你可以使用 sizeof(ref_to_int),在我的x64上使用gcc的结果为8。该字段存储引用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接