views:

643

answers:

1
if (vector1.x > ((float*)&vector1)[j])

Is j simply just an index into the vector?
e.g. is C++ able to retrieve these values using array notation even though vector isn't an array?
If so I'm guessing it achieves this by referencing vector by its address?

+10  A: 

The C++ Standard says that casting a (pods) struct's pointer to a pointer of the type of its first element will yield a pointer to its first element:

struct a {
    float a1;
    float a2;
    float a3;
};

a o1; ((float*)&o1); // points to o1.a1

I suspect that code told the compiler not to add any padding between a1, a2 and a3, so that if it indexes the pointer, it will pointer exactly to the float it wants. So above

((float*)&o1)[1] // *would* return o1.a2

That's platform dependent, as padding can't be changed in Standard C++. Lookup how that code arranges it, and whether i'm right at all :)

Johannes Schaub - litb
"casting a struct's pointer to a pointer of the type of its first element will yield a pointer to its first element". Even if the struct is non-POD?
Steve Jessop
Does this apply if vector is in fact a class?
Adam Naylor
pod structs must be aggregates. that means no user defined constructors, no copy assignment ops (i believe), only public stuff, no user defined destructor and stuff. in short, they have to be compatible with C code.
Johannes Schaub - litb
@Adam: it makes no difference whether it's a struct or a class, what matters is whether it's POD or non-POD.
Steve Jessop
I see. thanks for the info.
Adam Naylor
yeah. note that class a { public: float b; }; is exactly the same as struct a { float b; }
Johannes Schaub - litb
Ok. upon reflection the vector class in my example does appear to be pretty basic (POD). Although it does contain a couple of contrustors this should still qualify it as a POD class shouldn't it?
Adam Naylor
strictly no, but the visual c++ compiler includes a couple of guarantees that makes undefined behavior in defined one. for example, you can pass the mfc CString class to vararg functions (iirc), even tho only POD classes can be passed that way. Could be well the case this is just another example
Johannes Schaub - litb
next C++ will allow you to have constructors and still have pod classes, by declaring the default constructor as default (important for example for std::pair): struct x { x() = default; x(int a) :a(a){} int a; }; // pod
Johannes Schaub - litb
And if all the members are the same type, then the standard doesn't allow any padding between them.
Darron
Sounds interesting. Darron, can you please tell us where it says that? (never read something like that, and i've read the chapter about classes several times).
Johannes Schaub - litb