Search code examples
c++inheritancealignmenticc

Alignment of Child is Smaller Than Alignment of Base


After much deliberation, I have reduced a problem down to the following simple example:

//__declspec(align(16)) class Vec4 {}; //For testing purposes on Windows
//class Vec4 {} __attribute__((__aligned__(16))); //For testing purposes on *nix
class Base { public:
    Vec4 v; //16-byte-aligned struct
};
class Child : public Base {};
static_assert(alignof( Base)>=16,"Check 1");
static_assert(alignof(Child)>=16,"Check 2");

Check 1 passes; Check 2 fails. My question: Why?


In practice, allocating a Child (i.e. new Child) will cause v to be possibly 8-byte-aligned (v uses SSE, so this in turn causes a crash).

Compiler is Intel Compiler 2016. I tried g++ and Clang, and they seem okay. Is this maybe a compiler bug?


Solution

  • I have asked Intel directly. Although it could initially be reproduced by their team, after a few days, it couldn't be. Neither I nor they had an explanation. So, magic does exist, and no harm done.

    As to the actual substance of the question: yes, it appears that the alignment of the child should be at least as large as the alignment of the base, and a compiler that does not do this is in error.

    N.B. stack allocations respect the class's alignof, but malloc/new do not (how could they know?). As the other answer says, custom heap allocators must be used. This problem is separate from a correct alignof per se.