问题
Imagine a function like this:
function(Human *&human){
// Implementation
}
Can you explain what exactly a *& is? And what would it be used for? How is different than just passing a pointer or a reference? Can you give a small and explanatory sample?
Thank you.
回答1:
It is like a double pointer. You're passing the pointer by reference allowing the 'function' function to modify the value of the pointer.
For example 'human' could be pointing to Jeff and function could modify 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;
}
回答2:
void doSomething(int &*hi);
will not work. You cannot point to references. However, this:
void doSomething(int *&hi); // is valid.
It is a reference to a pointer. This is useful because you can now get this pointer passed into the function to point to other "Human" types.
If you look at this code, it points "hi" to "someVar". But, for the original pointer passed to this function, nothing will have changed, since the pointer itself is being passed by value.
void doSomething(int *hi)
{
hi = &someVar;
}
So you do this,
void doSomething(int *&hi)
{
hi = &someVar;
}
So that the original pointer passed into the function is changed too.
If you understand "pointers to pointers", then just imagine that, except when something is a reference it can be treated like a "non-pointer".
回答3:
"Takes an address of a pointer" - No, it doesn't. It takes supposed to take a reference to a pointer.
However, this is a syntax error. What you probably meant is
rettype function(Human *&human)
(Yes, it's also missing a return type...)
回答4:
Since you wrote this code off the top of your head, I'm going to assume you meant to do something like this:
void f(T *&) {}
This function signature allows the pointer passed to become modifiable, something that isn't allowed with the alternate syntax int *
. The pointer is effectively passed by reference as others here call it.
With this syntax, you are now able to modify the actual pointer and not just that which it points to. For example:
void f(int *& ptr) {
ptr = new int;
}
int main() {
int * x;
f(ptr); // we are changing the pointer here
delete x;
}
Summary (assume types are in parameters):
T *
: We are only able to change the value of the object to which the pointer points. Changing the parameter will not change the pointer passed.T *&
: We can now change the actual pointerT
, and the value of the object to which it points*T
.
回答5:
Even though it looks just like the address-of operator, it's not - it's a reference parameter. You use a reference when you want to be able to change the value at the caller's end. In this case the pointer is probably being set or changed within the function.
来源:https://stackoverflow.com/questions/13980482/c-function-parameter-takes-an-address-of-a-pointer-as-an-argument-how-is-this