i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.
I have basically this code
//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void func(const std::vector<std::string>& vec)
{
//I need to call otherFunc(void*) with a single element from vec:
//otherFunc(void* arg);
//with arg being a void* to vec[0]
}
My IDE tells me that only &*vec[0] works as parameter for otherFunc, but this doesn’t compile…
How is the best way to do these kind of parameter passing?
That is a good declaration, as long as the function is not intended to modify the vector. It’s more efficient than passing by value, since it avoids copying the vector – an expensive operation requiring a memory allocation.
However, the other function requires a non-const pointer. How to handle this depends on whether it might modify the data.
If it won’t (as you imply when you say “I’m only reading from it”) then the options are:
otherFunc(void const * arg)to give a stronger guarantee that it won’t, orconstqualification with aconst_cast<void*>when calling itNote that
&*vec[0]won’t compile; you wantvec[0].c_str()to get a C-compatible pointer to the first string’s data, assuming that’s what you need.If it might modify the vector, then you’ll have to do something else, since there’s no legal way to modify a
std::stringthrough a pointer to its data. Probably the best option is to usestd::vector<char>rather thanstd::string, but that depends on exactly what the function does.