5

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?

rubenvb
  • 74,642
  • 33
  • 187
  • 332

2 Answers2

3

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)

sehe
  • 374,641
  • 47
  • 450
  • 633
  • 2
    Actually the specification says that if that when the variadic type list is passed it is undefined behavior if it is an empty list ([see this](http://en.cppreference.com/w/cpp/types/aligned_union)) – DarthRubik Jul 06 '16 at 00:14
1

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])

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 1
    This is insightful, and I'd almost +1 for just that information. But how does it explain the presence of that initial template argument? – sehe Nov 21 '14 at 20:05
  • Well, a `union` is as big as the largest type it contains, surely that size would suffice for `aligned_union`'s `aligned_storage` as well? (except for the empty param pack situation @sehe mentions) – rubenvb Nov 21 '14 at 20:22
  • Can you edit this answer to bring the `[edit] To clarify` more prominence? – Yakk - Adam Nevraumont Nov 21 '14 at 21:54