Move the vector <T *> to the vector <const T *>

Is it possible to move a vector<T*> to vector<const T*> without copying and without using reinterpret_cast<> ? I.e.

 vector<int*> get() { return ...; } vector<const int*> getConst() { return whatgoeshere(get()); } 
+8
c ++ vector const
source share
2 answers

I'm going to attack it from a different angle. And consider a possible design problem. You did not specify what goes into ... , but provided that get fills the vector and then returns it, the solution in my opinion is to raise code that fills outside of both functions.

 template<typename Int> void do_get(std::vector<Int*>& v) { // Populate v } auto get() { std::vector<int*> ret; do_get(ret); return ret; } auto getConst() { std::vector<const int*> ret; do_get(ret); return ret; } 

One source of truth for human logic. And although the two original functions are identical, this is insignificant. In addition, with a reasonable implementation, it will not make extra copies, because the RVO is amazing.

+5
source share

Not.

Although T* can be trivially converted to const T* , the const T* container is not connected to the const T* container, so there is simply no way to do what you ask for.

Consider also that such functionality can hypothetically assign int** a const int** , which is unacceptable (there is no special case provided for the programmer when this task was performed as part of a swap operation, as far as I know).

In addition, a reinterpret_cast will simply crack these facts, exposing your program to undefined behavior.

You have three options:

  • Copy vector (O (n))
  • Make sure you have the container you want first (O (& infin;))
  • Make sure you don’t need a new type of container at all (O (?))
+3
source share

All Articles