问题:
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: 以下答案和链接的摘要:
- A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding. 可以多次分配指针,而绑定后不能重新分配引用。
- Pointers can point nowhere (
NULL
), whereas a reference always refers to an object. 指针不能指向任何地方(NULL
),而引用始终指向对象。 - You can't take the address of a reference like you can with pointers. 您不能像使用指针那样获取引用的地址。
- 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: 有趣的读物:
- My all-time favorite C++ FAQ lite . 我一直以来最喜欢的C ++常见问题lite 。
- References vs. Pointers . 参考与指针 。
- An Introduction to References . 参考文献简介 。
- References and const . 参考和const 。
解决方案:
参考一: 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
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3210516