Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class variables - alignment [duplicate]

Tags:

c++

operators

Possible Duplicate:
Classes store data members in sequential memory?

Just wanted to ask why the following is correct:

template<class T>
class Vec3 {
public:
  // values
  T x,y,z;

  // returns i-th komponent (i=0,1,2) (RHS array operator)
  const T operator[] (unsigned int i) const {
    return *(&x+i);
  }
}

or in other words: Why is it always guaranteed that x, y and z are always sizeof(T) units apart in memory. Can't there ever be fragmentation holes in between two of those varibles, thus letting this operator return a false value?

like image 679
user1709708 Avatar asked Jan 16 '13 14:01

user1709708


1 Answers

It is not guaranteed that x, y and z are always sizeof(T) units apart in memory. There can be padding bytes added in between.
It is left out as an implementation detail.
Only thing guaranteed is that there will be no padding between beginning of the class/structure and its first member for POD structures/classes.

It is not guaranteed that the implementation of operator[] in your code will work always.

Reference:
C++11: 9.2 Class members [class.mem]

14) Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).

like image 197
Alok Save Avatar answered Oct 29 '22 05:10

Alok Save