0

How can I find the size of boost::variant object when it contains elements such as std::string, std::vector, ...?

As the code below shows, with sizeof(t1.type()) or sizeof(t2.type()), I get a size of 16 bytes for both Type1 and Type2 variants.

With sizeof(t1) I get 8 bytes and sizeof(t2) is 32 bytes, and this does not depend from the length of the string contained in the variant.

Am I looking for the size in the right way?

In a boost::variant, is the size the same for all objects of the same variant, independently from their contents (like with C unions)? How are complex elements stored? By value or through a pointer?

    typedef boost::variant<bool, char, int> Type1;
    typedef boost::variant<bool, char, int, std::string> Type2;

    cerr << "Type1 = variant<bool, char, int> = " << sizeof(Type1) << endl;
    cerr << "Type2 = variant<bool, char, int, std::string> = " << sizeof(Type2) << endl;

    Type1 t1;
    Type2 t2;

    t1 = true;
    cerr << "Type1 bool = " << sizeof(t1.type()) << endl;
    t1 = 'a';
    cerr << "Type1 char = " << sizeof(t1.type()) << endl;
    t1 = 123;
    cerr << "Type1 int = " << sizeof(t1.type()) << endl;
    t2 = true;
    cerr << "Type2 bool = " << sizeof(t2.type()) << endl;
    t2 = 'a';
    cerr << "Type2 char = " << sizeof(t2.type()) << endl;
    t2 = 123;
    cerr << "Type2 int = " << sizeof(t2.type()) << endl;
    t2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    cerr << "Type2 string = " << sizeof(t2.type()) << endl;

Why this question is not a duplicate of What is boost::variant memory and performance cost? : here the answer is about basic data types, so they discuss about boost::variant as if it was an union. In my question I mix basic data types with an std::string. Please, remove the [duplicate] tag. Thank you.

Community
  • 1
  • 1
Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 2
    What do you mean by "size"? How do you plan to use one, once found? `sizeof(anything)` is a compile-time constant, returning the size in bytes of the type of `anything`. It can't possibly vary depending on the state of `anything` at runtime: `sizeof(std::string("a")) == sizeof(std::string("aaaaaaaa...a"))` – Igor Tandetnik Jul 23 '16 at 18:01
  • 1
    Thus, `boost::variant::type()` returns a reference to `std::type_info`. `sizeof(t1.type()) == sizeof(std::type_info)` - once again, a compile-time constant that doesn't depend on the state of `t1` at run time. – Igor Tandetnik Jul 23 '16 at 18:03
  • @Igor: I do not want to modify the size at runtime. What I need to know is how the size of variant objects is managed. E.g.: do the same rules valid for unions apply here, i.e. the size of the union is the size of the largest type? And what happens when one of these types is an int, and the other a std::string? I cannot imagine that memory for the largest possible string is allocated; a pointer should be what is effectively stored. – Pietro Jul 23 '16 at 20:15

0 Answers0