SmartVessel

Foucs on C++

博客园 首页 新随笔 联系 订阅 管理

Summary from answers and links below:

  1. A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
  2. A pointer can point to NULL while reference can never point to NULL
  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;

allocates the same amount of storage as a pointer, and places the address of i into that storage.

So pointer and reference occupies same amount of memory

As a general rule,

  • Use references in function parameters and return types to define attractive interfaces.
  • Use pointers to implement algorithms and data structures.

Interesting read:

posted on 2011-04-18 09:54  SmartVessel  阅读(374)  评论(0编辑  收藏  举报