Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "Pass by * &" for?

What does it mean? I understand the use of pass by reference is to pass in the reference so you can directly alter it without the need of a return, and pass by pointer is similar but with a slower runtime. However, I do not understand what * & does. For an example,

foo(int * & var) { }
like image 440
Goyatuzo Avatar asked Jan 26 '26 12:01

Goyatuzo


2 Answers

It passes a pointer by reference so that you can change what the pointer points to and have those changes reflected to the caller.

For example:

void notByReference(int *p) {
    p = nullptr;
}

void byReference(int *&p) {
    p = nullptr;
}

int main() {
    int *i = new int;
    notByReference(i); //i is not changed since a copy of the pointer was passed
    byReference(i); //i itself is changed, leaking memory
}
like image 183
chris Avatar answered Jan 28 '26 03:01

chris


This allows you to pass a pointer by reference. Which gives the function the opportunity to modify the pointer and have that modification seen by the caller.

You don't need to stop there. You can pass by reference a pointer to pointer to int, for example.

void foo(int** &var)
like image 36
David Heffernan Avatar answered Jan 28 '26 02:01

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!