memory allocation for a struct
If I define
Code:
struct A
{
float x,y,z;
A(xx,yy,zz) { x=xx;y=yy;z=zz;};
virtual ~A(void) {};
}
then
Code:
A a(0.0,1.0,2.0);
float* p2;
p2 = reinterpret_cast<float*>(&a);
float f;
f = p2 [2];
assert(f==a.z);
Can I be certain that the member variables of A will appear in memory in the right order like an array, in spite of the fact that A has a virtual function table? Is this part of the C++ spec? Is it true of all platforms and implementations?
Re: memory allocation for a struct
Quote:
Originally posted by c94wjpn
Can I be certain that the member variables of A will appear in memory in the right order like an array, in spite of the fact that A has a virtual function table?
I don't have the ANSI/ISO spec on hand, but classes / structures with user-defined destructors (and consstructors) have no guarantees where the first member is located.
Why not use an array in the structure instead of three separate float variables? Then you just define a member that returns the address of the array, or define an operator float*()
Code:
struct A
{
float coord[3];
A(float xx,float yy,float zz) { coord[0]=xx; coord[1]=yy;coord[2]=zz;};
virtual ~A(void) {};
float *GetCoords() { return coord; }
operator float*() { return coord; }
};
int main()
{
A MyA(1.0,2.0,3.0);
float *p = MyA; // No need to cast
}
Regards,
Paul McKenzie