Reputation: 3256
I have an std::vector<int*> v
and I'd like to prevent further writes to it. The C++ compiler does not accept this
const std::vector<const int*>& w = v;
but it accepts this
const std::vector<const int*>& w = reinterpret_cast<const std::vector<const int*>&>(v);
The latter does work with Microsoft's compiler, meaning that the int*
inside v
and const int*
inside w
have the same addresses in memory.
Does this work by chance, as an unspecified behavior, or is it valid C++ ? Does it work with all types inside the vector, like std::vector<std::shared_ptr<int>>
? If invalid, is there another way to do this cast ?
I know I could also copy the vector, but I'd like to avoid that, since my vectors are pretty big.
Upvotes: 3
Views: 622
Reputation: 75688
This is Undefined Behavior.
std::vector<const int*>
and std::vector<int*>
are two different classes (generated by the same template, but that is irrelevant). They cannot alias each other and you cannot reinterpret_cast
between them.
My solution is to use std::span
:
const std::span s{const_cast<const int* const*>(v.data()), v.size()};
This will create a const std::span<const int* const>
.
Upvotes: 8