指针变量和引用变量有什么区别?
最佳答案
指针可以重新赋值:
int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10);
引用不能重新绑定(bind),必须在初始化时绑定(bind):
int x = 5; int y = 6; int &q; // error int &r = x;
指针变量有自己的身份:一个独特的、可见的内存地址,可以用一元
&
运算符获取,一定量的空间可以用sizeof
运算符。在引用上使用这些运算符会返回一个与引用绑定(bind)的值相对应的值;引用自己的地址和大小是不可见的。由于引用以这种方式假定了原始变量的身份,因此将引用视为同一变量的另一个名称很方便。int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); // &x == &r assert(&p != &p2);
您可以将任意嵌套的指针指向提供额外间接级别的指针。引用仅提供一级间接。
int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; **pp = 2; pp = &q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2);
可以为指针分配
nullptr
,而引用必须绑定(bind)到现有对象。如果你足够努力,你可以将引用绑定(bind)到nullptr
,但这是 undefined并且不会表现一致。/* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &r = *static_cast<int *>(nullptr); // prints "null" under GCC 10 std::cout << (&r != nullptr ? "not null" : "null") << std::endl; bool f(int &r) { return &r != nullptr; } // prints "not null" under GCC 10 std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl;
但是,您可以引用一个值为
nullptr
的指针。指针可以遍历数组;您可以使用
++
转到指针指向的下一个项目,并使用+ 4
转到第 5 个元素。这与指针指向的对象大小无关。指针需要用
*
取消引用才能访问它指向的内存位置,而引用可以直接使用。指向类/结构的指针使用->
访问其成员,而引用使用.
。引用不能放入数组,而指针可以(用户@litb 提到)
Const 引用可以绑定(bind)到临时对象。指针不能(不是没有一些间接的):
const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary.
这使得
const &
更便于在参数列表等中使用。
关于c++ - 指针变量和引用变量有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764310/