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 :-