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