Search code examples
c++pointersvectorreinterpret-cast

Is it safe to reinterpret_cast as a smaller array? Is there a better option?


So, let's assume I have a custom vector type:

template <class D, size_t N>
class Vector {
public:
    
    Vector(const D* arrayPtr)
    {
        memcpy(m_array.data(), arrayPtr, sizeof(D)*N);
    }

    ... operators, methods, etc ...

    std::array<D, N> m_array;
};

So, I instantiate a new Vector<double, 4> pointer. However, sometimes I want to treat it as a Vector<double, 3>. Is it safe to do the following?

Vector4* myVec4 = new Vector4(1, 2, 3, 4);
Vector3* myVec3 = reinterpret_cast<Vector3*>(myVec4);

I would assume "maybe", since the class is contiguous in memory, and doesn't have any virtual methods. However, I want to be very sure before I make any risky moves.


Solution

  • No, that would not be safe because accessing the object through the incompatible pointer would result in undefined behaviour.

    To achieve something similar, you could instead use a class such as Vector3View that indirectly refers to the larger vector.