문제

I've started to build up a little data type and at the current stage I have only one recursive type in a boost variant. It turns out, I get a segfault when I try to instantiate my type. If I put a string before the recursive type it works, putting it after the type it doesn't. I'm using mingw with gcc 4.8.1 64bit and boost 1.54.

Am I using boost variant the wrong way?

#include <boost/variant.hpp>
#include <boost/variant/recursive_variant.hpp>

#include <string>
#include <iostream>

struct A;
struct B;

using C = boost::variant<boost::recursive_wrapper<A>>;

// works:
// using C = boost::variant<std::string, boost::recursive_wrapper<A>>;

struct A {
  std::string name;
  C variant;
};

struct B {
  std::string name;
  C variant;
};

int main() {

  std::cout << "start" << std::endl;
  B hAST; // <--- segfaults
  std::cout << "end" << std::endl;

  return 0;
}
도움이 되었습니까?

해결책

I believe this is due to the "never-empty" guarantee of variant: The default constructor of C must initialize itself with a default-constructed value of its first template parameter - which is recursive_wrapper<A> - and the default constructor of recursive_wrapper<A> must initialize itself with a default-constructed instance of A, which leads to infinite recursion.

Assuming you actually want a variant that is either empty, or an instance of A, you could introduce a dummy type as the variant's first parameter, for example:

struct variant_is_empty { };

using C = boost::variant<variant_is_empty, boost::recursive_wrapper<A>>;

EDIT: It appears you can use boost::recursive_wrapper with boost::optional, which would be easier than using variant for the above case of an optional, recursive type.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top