Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting pointers to const in container types

C++ provides implicit conversion from T * to const T *.

If I use T * within a container class now, like in vector<T *>, then there is of course no implicit conversion to vector<const T *> anymore.

Using an reinterpret_cast seems to work to cast the entire container, but is it actually safe to do this?

template <typename T>
const vector<const T *> & constVector(const vector<T *> & vec) {
    return reinterpret_cast<const vector<const T *> &>(vec);
}

// Usage:
vector<int *> vec1;
vector<const int *> vec2 = constVector(vec1);
like image 699
emkey08 Avatar asked Nov 22 '18 17:11

emkey08


1 Answers

but is it actually safe to do this?

No, this is undefined behavior. It is only safe to use reinterpret_cast in a very limited set of scenarios, please refer to cppreference.


If ownership is not a concern, you might want to use (or implement) a const view over a non-const range of objects. Googling for span would be a good start. std::string_view is an example of this for std::string.

like image 180
Vittorio Romeo Avatar answered Sep 22 '22 11:09

Vittorio Romeo