TITLE: alignment of character array (Newsgroups: comp.std.c++, 27 Oct 98) NARAN: sbnaran@fermi.ceg.uiuc.edu (Siemel Naran) >What is the alignment of char[N]. I want to be able to put any >object in this uninitialized space. CLAMAGE: stephen.clamage@sun.com (Steve Clamage) The alignment of an array of objects does not need to be any more stringent than the alignment of its element type. You are therefore not assured (by the C++ standard) that a variable or class member of type array-of-char will have any special alignment. (The alignment of a char is 1 by definition.) An implementation is allowed to use stricter alignment. OTOH, if you allocate raw storage with malloc or operator new, you are assured that the storage will be aligned suitably for any object that can be contained in the space. (If you write your own operator new, that is one of its constraints.) NARAN: >Is the following code >portable? It does work on egcs 1.1b and como 4.2.38 in Linux. >class Silly >{ > private: > enum { isA, isB } d_which; > char d_object[Max::VAL]; > A& asA() { return reinterpret_cast(d_object); } > B& asB() { return reinterpret_cast(d_object); } > > public: > Silly(const A& a) : d_which(isA) { new (&asA()) A(a); } > Silly(const B& b) : d_which(isB) { new (&asB()) B(b); } > ~Silly() > { > switch (d_which) > { > case isA: asA().~A(); break; > case isB: asB().~B(); break; > } > } >}; CLAMAGE: On what platforms, and for what kind of classes A and B, does it work? (Rhetorical question.) Some CPUs have no alignment restrictions, although performance improves when objects are suitably aligned. Intel's x86 chips have that property, for example, and your code would work. Other CPU's have important alignment requirements. For example, type double has an 8-byte alignment requirement on some CPUs. If class A contains a double, and the alignment of d_which is 4 bytes, on average half the A subobjects will be misaligned, and would cause a program abort when referenced. If neither A nor B has a non-trivial default constructor, you can create a union, which will be properly aligned. class Silly { ... union { // anonymous union A a; // access as 'a' member of Silly B b; // access as 'b' member of Silly }; ... }; Unfortunately, no object, not even a simple value object, that has a user-written default constructor can be placed in a union. If you make d_object a pointer and put the storage on the heap, the A and B objects will always be properly aligned.