-
Book Overview & Buying
-
Table Of Contents
C++ Memory Management
By :
Another area where a C++ programmer can get into trouble is type punning. By type punning, we mean techniques that subvert the language’s type system somewhat. The consecrated tool to perform type conversions is casts, as they are explicit in source code text and (apart from C-style casts) express the intent for the conversion, but that topic deserves its own chapter (Chapter 3, if you’re wondering).
In this section, we will examine other ways to achieve type punning, including both recommendable ones and others that you should seek to avoid.
A union is a type for which the members are all at the same address. The size of a union is the size of its largest member, and the alignment of a union is the strictest alignment of its members.
Consider the following example:
struct X {
char c[5]; short s;
} x;
// one byte of padding between x.c and x.s
static_assert(sizeof x.s == 2 &...