tags:

views:

85

answers:

3

See: http://stackoverflow.com/questions/3874615/placement-new-issue

Simple question, would this solve the align problem?

union
{
    char real_array[sizeof(T)*size];
    T    fake_array[size];
};
+1  A: 

I don't think so, if you look back at the link you posted it said 'OK I finally get it, it may start on a wrong address.' You still have no control over the address of the first member of the union.

James
The language standard guarantees that a pointer to any member of the union can also be used as a pointer to the entire union, and vice versa (after the appropriate conversion). One can argue that this immediately means that all members of a union must have the same physical address as the entire union itself (since there's no requirement for the union type to be complete at the point of conversion). I.e. all members of the union are aligned on the same boundary, the strictest among all members.
AndreyT
Sure, I was struggling to phrase it properly. 'First member' was a bad choice of words
James
+6  A: 

Yes, that should solve the alignment problem. There's no need to make fake_array an array though. Just a single member of type T is enough.

This is actually a rather widely used trick for forcing specific alignment on some array.

As a pedantic side-note: anonymous unions only exist in C++, but not in C.

AndreyT
+1  A: 

Yes, and even the simpler struct below could do the trick.

union
{
    char real_array[sizeof(T)*size];
    T    dummy;
};

I believe the citation below from ISO standard is guarantee enough that it works.

One special guarantee is made in order to simplify the use of unions: If a POD-union contains several POD-structs that share a common initial sequence, and if an object of this POD-union type contains one of the POD-structs, it is permitted to inspect the common initial sequence of any of POD-struct members;

However, as standard is worded you could wonder if there is not some loophole leading to Undefined Behavior if you use non POD classes... (but I would bet it will work with any compiler anyway).

kriss