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?
It is not guaranteed that
x,yandzare alwayssizeof(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]