简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM