【问题标题】:How does boost::variant store references?boost::variant 如何存储引用?
【发布时间】:2012-02-16 01:33:38
【问题描述】:

以下代码编译并执行“正确的事情”:

#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&amp;) == sizeof(T),所以不能使用sizeof() 运算符。现在,我知道引用最有可能实现为指针,但语言不能保证。当变体存储引用时,get&lt;&gt; 和访问如何工作的一个很好的解释得到了加分:)

【问题讨论】:

  • 通过将它们包装在一个对象中。 &lt;&lt; sizeof(std::vector&lt;char&gt;&amp;), sizeof(std::vector&lt;char&gt;), sizeof(T); struct T { std::vector&lt;char&gt;&amp; r; }; 56, 56, 8

标签: c++ boost boost-variant


【解决方案1】:

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

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。该字段存储引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多