While answering the question "Range based for loop for heap allocated arrays" today I stumbled upon the suggestion to use reinterpret_cast
to cast from a pointer type to an array-type using std::launder
(After some discussion we decided to post a new question, as we could not find a conclusion.). The cast was done as follows (lets say, e.g., in order to be able to use range-based loops to iterate over the array):
int* ptr = new int[3];
auto arr_ptr = std::launder(reinterpret_cast<int (*)[3]>(ptr));
I am almost certain this is UB, but I am not really sure. Is anyone firm enough in C++ to answer that?
I think this breaks down to the question if reinterpret_cast
is valid when casting from ptr-type to array-type, which I think is UB, and has nothing to to whether or not I use std::launder
.