C ++中的指针变量和引用变量之间有什么区别?

左心房为你撑大大i 提交于 2020-03-25 07:50:03

3 月,跳不动了?>>>

问题:

I know references are syntactic sugar, so code is easier to read and write. 我知道引用是语法糖,因此代码更易于读写。

But what are the differences? 但是有什么区别呢?


Summary from answers and links below: 以下答案和链接的摘要:

  1. A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding. 可以多次分配指针,而绑定后不能重新分配引用。
  2. Pointers can point nowhere ( NULL ), whereas a reference always refers to an object. 指针不能指向任何地方( NULL ),而引用始终指向对象。
  3. You can't take the address of a reference like you can with pointers. 您不能像使用指针那样获取引用的地址。
  4. There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5 ). 没有“引用算术”(但是您可以采用引用指向的对象的地址,并像&obj + 5那样对它执行指针算术)。

To clarify a misconception: 为了澄清一个误解:

The C++ standard is very careful to avoid dictating how a compiler may implement references, but every C++ compiler implements references as pointers. C ++标准非常小心,避免指出编译器如何实现引用,但是每个C ++编译器都将引用实现为指针。 That is, a declaration such as: 也就是说,这样的声明:

int &ri = i;

if it's not optimized away entirely , allocates the same amount of storage as a pointer, and places the address of i into that storage. 如果尚未完全优化 ,则分配与指针相同的存储量,并将i的地址放入该存储中。

So, a pointer and a reference both use the same amount of memory. 因此,指针和引用都使用相同数量的内存。

As a general rule, 作为基本规则,

  • Use references in function parameters and return types to provide useful and self-documenting interfaces. 在函数参数和返回类型中使用引用,以提供有用的自记录接口。
  • Use pointers for implementing algorithms and data structures. 使用指针来实现算法和数据结构。

Interesting read: 有趣的读物:


解决方案:

参考一: https://stackoom.com/question/Ex9/C-中的指针变量和引用变量之间有什么区别
参考二: https://oldbug.net/q/Ex9/What-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in-C
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!