Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a tuple guaranteed to compress empty elements?

The implementations of std::tuple in both libstdc++ and libc++ use (I presume) the empty base class optimisation to compress empty elements:

struct empty {};

static_assert(sizeof(std::tuple<int, empty>) == sizeof(int), ""); // (1)

My question is simply, is this behaviour mandated by the standard? That is, can I rely on (1) always being true for a standard-conforming implementation?

like image 337
Tristan Brindle Avatar asked Mar 11 '16 12:03

Tristan Brindle


1 Answers

No, that is not guaranteed. C++ 11 § 20.4 (the chapter about std::tuple) does not mention the size of the type at all. So there are no guarantees about how the members in a tuple are organised. Any empty-base optimisation and similar effects are purely a quality-of-implementation issue.

Note that this means there is even no guarantee that std::tuple<int, char> will be stored in memory as int followed by char and not vice versa. The layout of a std::tuple object is completely unspecified.

like image 166
Angew is no longer proud of SO Avatar answered Oct 05 '22 01:10

Angew is no longer proud of SO