Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::aligned_union need a minimum size as a template parameter?

Tags:

c++11

std::aligned_union has a std::size_t "minimum length" parameter. Now, a usual union does not have this, so I wonder why this is necessary. Could someone explain to me why?

like image 519
rubenvb Avatar asked Sep 30 '22 09:09

rubenvb


2 Answers

I wager this is for generic programming situations, where the variadic type list could be empty.

In that case, a certain minimum size will be used so that you still control the alignment (there would be no type to take the alignment value from)

like image 57
sehe Avatar answered Oct 03 '22 04:10

sehe


The relevant paper appears to be N2140. The reason fundamentally is that you can over-align types. The example given is that you can make a page-aligned data structure.

(I first had aligned_storage and aligned_union mixed up, sorry).

Aligned_storage is described in N2140 as the likely base class of aligned_union. N2140 also describes (but does not mandate) the implementation of point of aligned_storage<N, ...> as a warpper of an aligned char[N]. Obviously you need N for that.

Because it's a non-trivial trivial type ;)

std::aligned_union is a POD type with at least the given size, and alignment per the types specified. Those types need not be POD types, from which it becomes obvious that they can't be members.

What you can do, however, is use placement new to put a T[n] in that storage provided that the aligned_union is aligned for T and its size is at least sizeof(T[n])

like image 40
MSalters Avatar answered Oct 03 '22 04:10

MSalters