Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ member layout

Let's we have a simple structure (POD).

struct xyz
{
    float x, y, z;
};

May I assume that following code is OK? May I assume there is no any gaps? What the standard says? Is it true for PODs? Is it true for classes?

xyz v;
float* p = &v.x;
p[0] = 1.0f;
p[1] = 2.0f; // Is it ok?
p[2] = 3.0f; // Is it ok?
like image 886
demi Avatar asked Jan 18 '10 18:01

demi


3 Answers

The answer here is a bit tricky. The C++ standard says that POD data types will have C layout compatability guarantees (Reference). According to section 9.2 of the C spec the members of a struct will be laid out in sequential order if

  1. There is no accessibility modifier difference
  2. No alignment issues with the data type

So yes this solution will work as long as the type float has a compatible alignment on the current platform (it's the platform word size). So this should work for 32 bit processors but my guess is that it would fail for 64 bit ones. Essentially anywhere that sizeof(void*) is different than sizeof(float)

like image 195
JaredPar Avatar answered Sep 20 '22 20:09

JaredPar


This is not guaranteed by the standard, and will not work on many systems. The reasons are:

  • The compiler may align struct members as appropriate for the target platform, which may mean 32-bit alignment, 64-bit alignment, or anything else.
  • The size of the float might be 32 bits, or 64 bits. There's no guarantee that it's the same as the struct member alignment.

This means that p[1] might be at the same location as xyz.y, or it might overlap partially, or not at all.

like image 40
JSBձոգչ Avatar answered Sep 22 '22 20:09

JSBձոգչ


No, it is not OK to do so except for the first field.

From the C++ standards:

9.2 Class members
A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment.

like image 45
Khaled Alshaya Avatar answered Sep 23 '22 20:09

Khaled Alshaya