I was given a (C++) code where arrays are passed using
void fun(int *& name){...}
but what is the idea behind that? I guess it means "an array of references" but when you just pass a pointer to the first element that would be fine, wouldn't it? So what is the motivation to do it this way?
The function receives a reference to a pointer. This means that the function can not only modify the int
that is pointed to by name
, but also that changes to the pointer itself made within the function call will also be visible outside.
Example:
#include <iostream>
int* allocate()
{
return new int();
}
void destroy(int*& ptr)
{
delete ptr;
ptr = NULL;
}
int
main(int argc, char *argv[])
{
int* foo = allocate();
std::cout << foo << std::endl;
destroy(foo);
std::cout << foo << std::endl;
return 0;
}
Output is:
0x82dc008
0
It means that the function can modify the value of the pointer in the caller.
i.e.
myName* foo; /* ToDo - initialise foo in some way*/
fun(foo);
/* foo might now point to something else*/
I regard this as an anti-pattern. The reason being that people reading your code will not expect foo
to be modified in such a way since the calling syntax is indistinguishable from the more normal function void anotherFun(int * name){...}
.
The stability of such code can suffer. As such, I'd recommend your using void fun(int ** name){...}
. The calling syntax then becomes fun(&foo)
which indicates to the function user that foo
might be modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With