Search code examples
c++arrayspointersc++11reinterpret-cast

Is c++ final non-virtual class reinterpreted as array safe for use?


I've got a non-virtual final class that declares only same type fields.

struct Vector3 final
{
    float X, Y, Z;
    Vector3(float x, float y, float z) : X(x), Y(y), Z(z)
    {

    }

    float Sum()
    {
        return X + Y + Z;
    }
};

Is it safe to reinterpret pointer to instance of this class to array of floats?

int main(int argc, const char *argv[])
{
    Vector3 v(10, 20, 30);
    Vector3 *pV = &v;
    float *ff = reinterpret_cast<float*>(pV);

    std::cout << ff[0] << std::endl << ff[1] << std::endl << ff[2] << std::endl;

    char c;
    std::cin >> c;

    return 0;
}

Solution

  • It's safe, but beware breaking strict aliasing!

    In C++11 jargon your struct is Standard Layout, hence it's safe to cast it via reinterpret_cast to its first member:

    § 9.2.20 Class members [class.mem]

    A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

    The subsequent floats are then contiguous in memory, just like an array.


    Why dont you provide an operator[]?