Class structure guaranteed access order

Consider this:

class Vec3
{
    private:
        float n[3];
    public:
        float& x;
        float& y;
        float& z;
        Vec3(float x_, float y_, float z_) : x(n[0]), y(n[1]), z(n[2])
        {
            x = x_;
            y = y_;
            z = z_;
        }
}

Can I be sure that it is:

Vec3 v(1,2,3);
cout<<reinterpret_cast<float*>(&v)[0]<<"\t";
cout<<reinterpret_cast<float*>(&v)[1]<<"\t";
cout<<reinterpret_cast<float*>(&v)[2]<<"\t";

will provide me with 1 2 3every compiler / OS following standard?

+3
source share
3 answers

As stated in other answers, this will not work because of float&. See Standard Layout Classes and Trivially Copy Types for a detailed explanation of the standard layout.

You may consider a slightly different approach:

class Vec3
{
    private:
        float n[3];
    public:
        float& x() { return n[0]; }
        float& y() { return n[1]; }
        float& z() { return n[2]; }
        Vec3(float x_, float y_, float z_)
        {
            x() = x_;
            y() = y_;
            z() = z_;
        }
};

In this way,

Vec3 v(1,2,3);
cout<<reinterpret_cast<float*>(&v)[0]<<"\t";
cout<<reinterpret_cast<float*>(&v)[1]<<"\t";
cout<<reinterpret_cast<float*>(&v)[2]<<"\t";

Will be printed 1 2 3for all compilers

Edit

You can also see What are aggregates and POD (1st answer) and What are aggregates and POD (2nd answer) for more accurate information.

+3
source

. ( ) . float& , Vec3 . (9/7, ).

+5

Nope. Your class is not a POD, so there is no guarantee, AFAIK.

+1
source

All Articles