-1

What is the difference between * and *& in function parameters. For example,

What is the difference between this,

void a(SomeType *s)
{

}

and this,

void a(SomeType *&s)
{

}
Fish
  • 1,205
  • 1
  • 10
  • 12

3 Answers3

3

First, let's add some "meat" to a:

void a1(SomeType *s)
{
    s = new SomeType;
}

void a2(SomeType *&s)
{
    s = new SomeType;
}

Now assume you have this code, which calls a:

void func()
{
    SomeType *p1 = nullptr;
    a1(p1);
    if (p == nullptr)
        std::cout << "p1 is null" << std::endl;
    else
        std::cout << "p1 is not null" << std::endl;

    SomeType *p2 = nullptr;
    a2(p2);
    if (p == nullptr)
        std::cout << "p2 is null" << std::endl;
    else
        std::cout << "p2 is not null" << std::endl;
}

a1 accepts a pointer, so the variable s is a copy of the pointer p1. So when a returns, p1 is still nullptr and the memory allocated inside a1 leaks.

a2 accepts a reference to a pointer, so s is an "alias" to p2. So when a2 returns p2 points to the memory allocated inside a2.

Generally, see What's the difference between passing by reference vs. passing by value?. Then apply that knowledge to pointers.

Community
  • 1
  • 1
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
2

When you pass a reference (using &) into a function, you can modify the value and the modifications will not be local. If you don't pass a reference (no &), the modifications will be local to the function.

#include <cstdio>
int one = 1, two = 2;

// x is a pointer passed *by value*, so changes are local
void f1(int *x) { x = &two; }

// x is a pointer passed *by reference*, so changes are propagated
void f2(int *&x) { x = &two; }

int main()
{
    int *ptr = &one;
    std::printf("*ptr = %d\n", *ptr);
    f1(ptr);
    std::printf("*ptr = %d\n", *ptr);
    f2(ptr);
    std::printf("*ptr = %d\n", *ptr);
    return 0;
}

Output:

*ptr = 1
*ptr = 1
*ptr = 2
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
0

In first case the function accepts the value of a pointer. In second case the function accepts non-constant reference to the pointer variable and that means that you can change this pointer location through the reference.

Zorgiev
  • 794
  • 1
  • 7
  • 19