Question

Is it well defined to cast to an identical layout with const members?

Consider the following type:

template<typename T> struct View
{
    T*     data;
    size_t size;
};

Is it valid to cast from: View<T>& To View<const T>&?

Does it invoke undefined behaviour?

I suspect the cast will work as intended on all compilers but will be technically undefined behaviour according to the standard due to the strict aliasing rule.

 7  290  7
1 Jan 1970

Solution

 8

View<T> and View<const T> are unrelated types and therefore casting a reference from the first to the second violates the strict aliasing rules and causes UB (undefined behavior).

It is true that is it valid to cast a T* to const T* (because these are related types), but this is not relevant when casting a reference to a class containing such members (View).

It might work as you expect on your compiler, but it is still undefined behavior by the standard and so I would not advise to rely on it.

As @FrançoisAndrieux commented above, you can cope with it by adding a converting constructor or conversion operator to allow converting from View<T> to View<const T>.

2024-07-05
wohlstad