Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty class in std::tuple

The size of any object or member subobject is required to be at least 1 even if the type is an empty class type [...], in order to be able to guarantee that the addresses of distinct objects of the same type are always distinct.

cppreference quote

This I knew. What I just found out is that some library types, like std::tuple don't use any size for contained empty classes. Is this true? If yes, how is that ok?


Edit: after reading @bolov's final note on his answer I still one question: since Empty is POD it is safe to memcpy to it. But if you would memcpy to a "phantom" address (see @bolov's answer) you would effectively write inside an int element (sizoef(Empty) is 1). That doesn't seem ok.

like image 734
bolov Avatar asked Aug 19 '16 12:08

bolov


People also ask

What is a std :: tuple?

Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair. If std::is_trivially_destructible<Ti>::value is true for every Ti in Types , the destructor of tuple is trivial.

Is std :: tuple a container?

The new std::array and std::tuple containers provide developers with additional ways to manage structured data efficiently.

Is there tuple in C++?

Tuples in C++A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.

Are tuples immutable C++?

Tuples are immutable. Lists are mutable. Tuples can contain different data types. Lists consist of a singular data type.


1 Answers

The size of an object must be greater than zero. The size of a subobject does not have that constraint. This leads to the Empty Base Optimization (EBO), in which an empty base class does not take up space (compilers started implementing this nearly 20 years ago). And that, in turn, leads to the usual implementation of std::tuple as an inheritance chain, in which empty base classes don't take up space.

like image 84
Pete Becker Avatar answered Oct 12 '22 02:10

Pete Becker