The C ++ function parameter takes the address of the pointer as an argument. How is it used? What is this for?

Imagine a function like this:

function(Human *&human){ // Implementation } 

Can you explain what * & is exactly? And what will it be used for? How is it different from a simple pointer or link? Can you give a small and explanatory sample?

Thanks.

+4
source share
5 answers

It is like a double pointer. You pass a pointer by reference, allowing the function to change the value of the pointer.

For example, a “person” may point to Jeff, and a function may change it to point to Ann.

 Human ann("Ann"); void function(Human *& human) { human = &ann; } int main() { Human jeff("Jeff"); Human* p = &jeff; function(p); // p now points to ann return 0; } 
+5
source
 void doSomething(int &*hi); 

will not work. You cannot point to links. However, this:

 void doSomething(int *&hi); // is valid. 

This is a link to a pointer. This is useful because now you can pass this pointer to a function to point to other types of Human.

If you look at this code, it points “hi” to “someVar”. But, since the original pointer passed to this function, nothing will change, since the pointer itself is passed by value.

 void doSomething(int *hi) { hi = &someVar; } 

So you do it

 void doSomething(int *&hi) { hi = &someVar; } 

So the original pointer passed to the function also changes.

If you understand “pointers to pointers,” then just imagine that, unless something is a link, it can be considered as “not a pointer”.

+7
source

"Accepts the address of the pointer" - No, it is not. It takes to take a reference pointer.

However, this is a syntax error. You probably meant

 rettype function(Human *&human) 

(Yes, it also has no return type ...)

+5
source

Since you wrote this code from the top of your head, I'm going to assume that you wanted to do something like this:

 void f(T *&) {} 

This function signature allows the passed pointer to become modifiable, which is not allowed with the alternative int * syntax. The pointer is effectively passed by reference, as others here call it.

With this syntax, you can now change the actual pointer, not just the one it points to. For instance:

 void f(int *& ptr) { ptr = new int; } int main() { int * x; f(ptr); // we are changing the pointer here delete x; } 

Summary (assuming types are in parameters):

  • T * : We can change the value of the object that the pointer points to. Changing a parameter will not change the passed pointer.
  • T *& : Now we can change the actual pointer T and the value of the object it points to *T
+5
source

Despite the fact that it looks the same as the address of the operator, it is not a reference parameter. You use the link when you want to change the value at the end of the caller. In this case, the pointer is likely to be set or changed inside the function.

+4
source

All Articles