|
-
February 26th, 2003, 04:38 AM
#1
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?
-
February 26th, 2003, 06:13 AM
#2
Re: memory allocation for a struct
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
-
February 26th, 2003, 06:39 AM
#3
Don't know about what the ANSI standart says
about all this, but when I use something like this
struct foo
{
int a;
int b;
foo( int _a, int _b ) : b(_b), a(_a) {}
};
my linux gc++ gives a warning and says
to initialize a struct members in the order by
wich they were declared, like
foo( int _a, int _b ) : a(_a), b(_b) {}
And as I ussulay saw, members of classes(structs)
has a order in the memory like they were declared
in the definition (a, b).
About virual functions. Ussualy if class has
some virtual function, then object has a
vtbl pointer before data members in the memory.
So of so and a object of this struct has a vtbl,
so p[0] = vtbl, and only then data members are stored.
But I want to notice that it is nothing about this in the standart.
It depends of compiler wich generate a code.
"UNIX is simple; it just takes a genius to understand its simplicity!"
-
February 26th, 2003, 07:07 AM
#4
This warning just says that the member variables are initialized in the order they appear in the class definition and not in the order that you use.
I. e.
Code:
struct foo
{
int a;
int b;
foo( int _a, int _b ) : b(_b), a(_a) {}
};
does not imply that the constructor for b is called before the constructor for a, but vice versa due to the definition order for a and b;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|