I want to construct an object of class T
by using ::operator new(size_t)
and placement new
.
To "extend" the size of char v[1]
, which is the last declared data member in T
, I allocate sizeof(T) + n - 1
bytes with operator new()
, where n
is the wanted size in bytes. This trick allows me to access v[i]
for any i
in [0, n -1]
.
My questions are about the C++ standard:
Does the order of declaration of data members in T
reflect the order in which data is represented in memory?
If the order is preserved, are data member alignments also preserved no matter how bigger is the size of the allocated memory?
1) Yes. From the section on pointer comparisons, the standard states that pointers to later members must compare as greater than pointers to earlier members. Edit: As pointed out by Martin, the standard only mandates this for POD structs.
2) Yes. Data alignment is not affected by the size of the allocation.
The thing is, nothing in the standard actually guarantees that the trick of using arrays this way works (IIRC).
struct something {
...
char buf[1];
};
However, this is done so commonly that it is a de-facto standard. The standards folks, last time I checked, were working on a way that they could codify these existing practices (It's already made its way into the C standard and it's only a matter of time before it's standardized in C++).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With