0

I am trying to implement pimpl without heap (adapt from a SO question).
I think I should reserve char[] myself, and hardcode alignment = 8.
However, I am very new to C++ alignment. I am afraid that 8 is not enough.

My study

After some reading, I understand that alignof is maximum size of internal field.

I have experimented :-

struct A {   //size = 16     alignof = 8 (max{4,1,8})
    int n;         //address = [0,4)
    bool flag;     //address = [4,5)
    double k;      //address = [8,16)
}; 
struct B{    //size = 24     alignof = 8 (max{A,1})
     A a;      //address = [0,16)
     char c;   //address = [16,24)    24=16+8(align)
};

From the experiment, I think alignment for my pimpl should be = 8 (conservative).
It should be safe as long as maximum primitive size is 8.
Reference: largest primitive type has at least 8 bytes. (but let's assume it is actually 8 bytes)

Question

Are there any cases that I should set alignment > 8?
In other words, is 8-bytes enough for all practical cases?

I believe that the answer is "it is safe", but a SO question confused me.
Here is a part of the question :-

The “memset_16aligned” function requires a 16byte aligned pointer passed to it, or it will crash.

I have also read :-

Community
  • 1
  • 1
javaLover
  • 6,039
  • 2
  • 14
  • 57
  • 1
    There is no standard `memset_16aligned` function. It could be a compiler-specific function that the compiler uses as an optimization for the standard `memset` call (or when otherwise zeroing memory), and then the compiler can use it because it will know the alignment is correct. That function is not something you should worry about in normal cases. – Some programmer dude Mar 21 '17 at 09:56
  • @Some programmer dude Thank! What about [warning C4316: object allocated on the heap may not be aligned 16](http://stackoverflow.com/questions/20104815/warning-c4316-object-allocated-on-the-heap-may-not-be-aligned-16)? I guess it is a not-so-normal case too, right? – javaLover Mar 21 '17 at 09:59
  • 1
    That seems to be some special case for a DirectX structure. When creating games or otherwise communicating with the systems GPU alignment matters more. In the general case you should not need to worry about it, and only handle it as special cases when the need arises. – Some programmer dude Mar 21 '17 at 10:02

0 Answers0