c++: pointer VS reference

本文详细解析了C++中引用与指针的特性,包括它们的赋值、指向空值的能力、内存占用情况以及在函数参数和返回类型中的应用。通过比较,清晰地展示了两者在实际编程中的不同用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in

https://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf


Summary from answers and links below:

  1. A pointer can be re-assigned any number of times while a reference can not be re-seated after binding.
  2. Pointers can point nowhere (NULL), whereas reference always refer to an object.
  3. You can't take the address of a reference like you can with pointers.
  4. There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).

To clarify a misconception:

The C++ standard is very careful to avoid dictating how a compiler must implement references, but every C++ compiler implements references as pointers. 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.

So, a pointer and a reference both occupy the same amount of memory.

As a general rule,

  • Use references in function parameters and return types to define useful and self-documenting interfaces.
  • Use pointers to implement algorithms and data structures.

Interesting read:

================总结================

C++编译器使用指针来实现引用。

对于指针,需要使用 * 来 解引用(dereference);对于引用,解引用是编译器自动完成的。(可以查看使用“引用的”汇编代码来确认。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值