3

See: Placement new issue

Simple question, would this solve the align problem?

union
{
    char real_array[sizeof(T)*size];
    T    fake_array[size];
};
Community
  • 1
  • 1
Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
  • 2
    For practical use, you'll want to look into Boost's/C++0x's `aligned_storage` and `alignment_of`. – GManNickG Oct 06 '10 at 21:18
  • 1
    It is not going to work for the cases you are interested in (avoiding calling constructors on unused array contents) - since T is only allowed to be a POD (where you don't need any of this, since they don't have constructors that do something). – UncleBens Oct 07 '10 at 07:06

3 Answers3

6

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

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
  • 9,064
  • 3
  • 31
  • 49
  • 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. – AnT stands with Russia Oct 06 '10 at 21:21
  • Sure, I was struggling to phrase it properly. 'First member' was a bad choice of words – James Oct 06 '10 at 21:36
1

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
  • 23,497
  • 17
  • 97
  • 116