Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data alignment in C++, standard and portability

Tags:

c++

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:

  1. Does the order of declaration of data members in T reflect the order in which data is represented in memory?

  2. If the order is preserved, are data member alignments also preserved no matter how bigger is the size of the allocated memory?

like image 747
pipex Avatar asked Oct 25 '22 03:10

pipex


1 Answers

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++).

like image 181
Dietrich Epp Avatar answered Oct 27 '22 09:10

Dietrich Epp