Search code examples
c++vectorreinterpret-cast

vector with reinterpret_cast


The following code inserts only one value to the vector col. The code is extracted from DBMS code base (for importing files), specifically, it is from 1

The code uses void* to be able to read any field type (int, float, and so on).

#include <iostream>
#include <vector>
using namespace std;

void add(std::vector<void*> &col){
  reinterpret_cast<std::vector<int>&>(col).push_back( 1);
  reinterpret_cast<std::vector<int>&>(col).push_back( 2);
  reinterpret_cast<std::vector<int>&>(col).push_back( 13);
}
int main() {
 std::vector<void*> col;

 add(col);
 cout << col.size() << endl;
 for(int i=0;i<col.size();i++)
    cout <<reinterpret_cast<std::vector<int>&> (col)[i] <<endl;
    return 0;
}

I am not sure how this code work?


Solution

  • Your code is exhibiting undefined behavior.

    std::vector<void*> and std::vector<int> are two completely separate and unrelated types, you can't safely cast between them the way you are, especially since there is no guarantee that void* and int are the same byte size.

    Cast the values you are pushing, don't cast the vector itself, eg:

    #include <iostream>
    #include <vector>
    #include <cstdint>
    using namespace std;
    
    void add(std::vector<void*> &col) {
        col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(1)));
        col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(2)));
        col.push_back(reinterpret_cast<void*>(static_cast<intptr_t>(13)));
    }
    
    int main() {
        std::vector<void*> col;
    
        add(col);
    
        cout << col.size() << endl;
        for(int i=0;i<col.size();i++)
            cout << reinterpret_cast<intptr_t>(col[i]) << endl;
    
        return 0;
    }
    

    Of course, you really should be using the proper container type to begin with:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    void add(std::vector<int> &col) {
        col.push_back(1);
        col.push_back(2);
        col.push_back(13);
    }
    
    int main() {
        std::vector<int> col;
    
        add(col);
    
        cout << col.size() << endl;
        for(int i=0;i<col.size();i++)
            cout << col[i] << endl;
    
        return 0;
    }