Search code examples
pointerscontainersreinterpret-cast

Is it practically safe to cast container of T* to container of const T*?


For instance,

std::vector<SomeNonCopyableType*> values = getVector();
auto &cvalues = reinterpret_cast<std::vector<const SomeNonCopyableType*>&>(values);

// use cvalues...

This is not allowed in standard of course. However, constness of pointed type won't make any difference in implementation detail unless they're specialized. In this case, may I consider this conversion is safe practically?

If it is a bad idea, is there graceful way to make a container of pointer to const from container of pointer to non-const without making copy?


Solution

  • Practically speaking yes, but it's not what you should be doing. Instead of aliasing the container, use its const_iterator type to work with the range of elements contained in the container. (You can use the experimental std::experimental::ranges::Range struct to help with this if you like.)