简体   繁体   中英

Conversion from 'void *' to 'vector<int *>'

I am casting a vector pointer as a void pointer to a function. In that function, how to I cast it to a vector pointer?

in main

vector<int *> foo;
function(&foo);

in function
function(void *bar){
    auto temp = bar; // what replaces auto or what should bar be cast to?
    temp.pushback(something);
}

I hope I have not mangled the terminology, any opinion helps!

You are not casting it, but thats just an implicit conversion. The method is called push_back and you need -> to dereference.

If you are absolutely certain that the void* points to a vector<int*> you can safely cast it back:

#include <vector>

void function(void *bar){
    auto temp = static_cast<std::vector<int*>*>(bar);
    temp->push_back(new int);
}

int main() {
    std::vector<int *> foo;
    function(&foo);
}

However, the question arises: Why all the pointers? If by any means you can change function and the vector is supposed to store integers your code should look like this:

#include <vector>

void function(std::vector<int>& v){
    v.push_back(42);
}

int main() {
    std::vector<int> foo;
    function(foo);
}

You can apply static_cast .

Here is a demonstrative program.

#include <iostream>
#include <vector>

void function( void *bar )
{
    auto pv = static_cast<std::vector<int *> *>( bar );
    
    for ( const auto &p : *pv ) std::cout << *p << ' ';
    std::cout << '\n';
}

int main() 
{
    int a[] = { 1, 2, 3 };
    std::vector<int *> v;
    
    for ( auto &x : a ) v.push_back( &x );
    
    function( &v );
    
    return 0;
}

The program output is

1 2 3

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