Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pass array as "int *& name"?

Tags:

c++

arrays

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?

like image 389
Hagadol Avatar asked Aug 29 '14 07:08

Hagadol


2 Answers

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
like image 75
oxygene Avatar answered Oct 12 '22 19:10

oxygene


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.

like image 26
Bathsheba Avatar answered Oct 12 '22 20:10

Bathsheba