Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does boost::variant store references?

The following code compiles and does the "right thing" :

#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;
}

How does boost::variant store a reference? According to C++ standard, how references are stored is completely up to the compiler. Actually, how does boost::variant even know how many bytes is taken up by a reference? sizeof(T&) == sizeof(T), so it can't be using sizeof() operator. Now, I know references are most probably implemented as pointers, but there is no guarantee in the language. A good explanation of how get<> and visitation works when the variant is storing references get extra points :)

like image 911
keveman Avatar asked Feb 16 '12 01:02

keveman


1 Answers

You can declare struct fields as references.

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

You can take the sizeof(ref_to_int), which is 8 on my x64 with gcc. The field stores the reference.

like image 165
Laurent LA RIZZA Avatar answered Oct 18 '22 23:10

Laurent LA RIZZA