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<>变体存储引用时如何和访问如何工作的一个很好的解释得到了加分:)

4

1 回答 1

7

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

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

您可以使用 gcc 在我的 x64 上的sizeof(ref_to_int). 8该字段存储引用。

于 2014-01-16T12:42:07.597 回答