Search code examples
c++functionpointersreferencevoid-pointers

Passing a void* by reference


Why can't I pass a void* by reference? The compiler allows me to declare a function with the following signature:

static inline void FreeAndNull(void*& item)

But when I try to call it, I get the following error:

Error   1   error C2664: 'FreeAndNull' : cannot convert parameter 1 from 'uint8_t *' to 'void *&'

Casting it to void* doesn't work either

Also, are there any workarounds?


Solution

  • If you take a void * by reference, you have to pass an actual void *, not an uint8_t *.

    Try this instead:

    template<typename T> inline void FreeAndNull(T * & V) { free(V); V = 0; }
    

    EDIT: Modified sample to better reflect the OP's function name, and to address @6502's entirely correct comment.