Question

I'm looking through an API written in C++ and I'm confused as to what the following parameter type means:

void*& data

Does that mean the user would pass in a reference to a void pointer? If that's true, what's the point? I mean void* is already indirected so why would you ever want to redirect it again?

Was it helpful?

Solution

It's tough to say without seeing it's use, but you point out that a reference is a level of indirection. Would you find it weird if it was a pointer to a pointer? Those are quite common - in fact you deal with them when accepting command line arguments and get pointers to char pointers. Another example would be if you were making a hash map using buckets, and wanted to be able to return the pointer to the pointer that started the bucket.

The point being is that sometimes you need multiple levels of indirection. It is true that mixing pointers and references can be quirky, but there are good reasons for it. One common reason is the need for C++ code to interact with C apis. A lot of POSIX system calls require void pointers that get passed in and then changed, so the C++ function in question may be acting as a wrapper around that.

OTHER TIPS

void * means pass-by-pointer in C++, meaning you pass in a pointer, but it's actually a copy of the pointer. If you modified this pointer in your function, like changing its address, it is not reflected in the pointer you passed in.

Combining that with pass by reference, void *& means you are passing an alias of the original pointer to this function. If you modified it, like changing its address, it will be reflected in the original pointer.

But be careful to not return reference to local void*. Don't do something like this:

void*& f()
{
 int* a=new int(10);
 void* x=(void*)a;
 return x;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top