What is the difference between * and *& in C++?
This question already has an answer here:
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.
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 = %dn", *ptr);
f1(ptr);
std::printf("*ptr = %dn", *ptr);
f2(ptr);
std::printf("*ptr = %dn", *ptr);
return 0;
}
Output:
*ptr = 1 *ptr = 1 *ptr = 2
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.
链接地址: http://www.djcxy.com/p/20600.html上一篇: 函数返回int&
下一篇: *和*在C ++中有什么区别?
