can someone explain max_aligh union mentioned Sutter's book

P

puzzlecracker

Why Attempt #3 is Deplorable

First, let's consider a few reasons why Attempt #3 above truly is
deplorable form:

1. Alignment. Unlike dynamic memory acquired by ::eek:perator new(), the
x_ character buffer isn't guaranteed to be properly aligned for
objects of type X. To make this work more reliably, the programmer
could use a "max_align" union, which is usually implemented as
something like:

union max_align {
short dummy0;
long dummy1;
double dummy2;
long double dummy3;
void* dummy4;
/*...and pointers to functions, pointers to
member functions, pointers to member data,
pointers to classes, eye of newt, ...*/
};

It would be used like this:

union {
max_align m;
char x_[sizeofx];
};

I don't understand how this will fix the alignment issue.

Thanks
 
S

SeanW

I don't understand how this will fix the alignment issue.

You don't say what book you're referring to, so I don't
know what "attempt #3" looks like, but I will note that
if you have a structure like:

struct S {
char m[sizeof(int)];
};

the compiler will likely feel justified putting it at
any alignment it wants, but if have a structure like:

struct S {
int m;
};

it will *always* put it at alignments suitable for m to
be accessed by the CPU (usually at N-byte boundaries,
where N is sizeof(int)).

The union just forces the compiler to align the
object at M-byte boundaries, where M is the largest
alignment-needing-thing in the union.

Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top