Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sizeof( std::variant< char > ) == 8 when using libc++ and not 2 (like with MSVC's STL and libstdc++)?

Tags:

People also ask

What is the size of a std :: variant?

Size of a Variant Datatype is always 16 bytes.

What is the size of a variant?

The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length),and can store any character text. How do you register a component?

Does std :: variant allocate?

One additional thing is that std::variant does not dynamically allocate memory for the values. Any instance of std::variant at any given time either holds a value of one of its alternative types, or it holds no value at all.

Can std :: variant be empty?

Empty variants are also ill-formed (std::variant<std::monostate> can be used instead). A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.


Consider this example on Compiler explorer.

Basically, we have this code snippet:

#include <cstdint>
#include <variant>

enum class Enum1 : std::uint8_t { A, B };

enum class Enum2 : std::uint8_t { C, D };

using Var = std::variant< Enum1, Enum2 >;
using Var2 = std::variant< char >;

template< std::size_t s >
struct print_size;

void func() {
    print_size< sizeof( Var ) >{};
    print_size< sizeof( Var2 ) >{};
}

If we compile this with GCC's libstdc++ (using either clang or GCC), we get the expected compile error:

error: implicit instantiation of undefined template 'print_size<2>'

Also, similar with MSVC (as expected):

error C2027: use of undefined type 'print_size<2>'

However, when using clang with libc++, I get this error:

error: implicit instantiation of undefined template 'print_size<8>'

This indicates that sizeof( std::variant< char > ) == 8 when using libc++. I've confirmed that on Linux (see compiler explorer link above), but also with Android's NDK r18 and Xcode 10 (both iOS and MacOS).

Is there a reason for libc++'s implementation of std::variant to use so much memory or is this simply a bug in libc++ and should be reported to libc++ developers?