Why pass an array as "int * & name"?

I was provided with code (C ++) in which arrays are passed using

void fun(int *& name){...} 

but what is the idea of ​​this? I suppose this means an "array of links", but when you just pass a pointer to the first element, which will be fine, right? So what is the motivation to do it this way?

+6
source share
2 answers

The function gets a reference to a pointer. This means that the function can not only change the int that name points to, but also that changes to the pointer itself made inside the function call will also be visible from the 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:

 0x82dc008 0 
+5
source

This means that the function can change 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 view this as an anti-pattern. The reason is that people reading your code do not expect foo to change this way, because the call syntax is indistinguishable from the more normal function void anotherFun(int * name){...} .

The stability of such a code may be affected. Therefore, I recommend using void fun(int ** name){...} . Then the call syntax becomes fun(&foo) , which tells the user of the function that foo can be changed.

+2
source

Source: https://habr.com/ru/post/974533/


All Articles