
我知道引用是语法糖,用起来方便。但是它们之间到底有啥区别呢?
int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);引用不可以,且必须初始化。 int x = 5;
int y = 6;
int &r = x;int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2);int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; pp = &q; // *pp = q **pp = 4; assert(y == 4); assert(x == 0);int *p = nullptr; int &r = nullptr; // compiling error int &r = *p; // likely no compiling error, especially if the nullptr is hidden behind a function call, yet it refers to a non-existent int at address 0++就可以拿到下一个位置的指针,+4就可以拿到后面的第四个。*来取值,引用不用。指向结构体或类对象的指针,还可以以->来获取其内部的成员,引用则使用.。const int &x = int(12); // legal C++ int *y = &int(12); // illegal to dereference a temporary.const std::string& name,还有单例模式中的引用返回。注意,C++ 标准并没有明确要求编译器该如何实现引用,但是基本上所有编译器在底层处理上都会把引用当作指针来处理。比如下面是一个引用,
int &ri = i;如果未被编译器完全优化,那么它的底层实现其实就和指针一样,开辟一段内存,存放 i 的地址。可以参考,
另外附一些可能需要的链接,
来自: https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in