Fork me on GitHub

6/02/2011

[C++] Reference 和 Pointer 的差異

在 C++ 當中 Reference 和 Pointer 都是一種間接取值的方法,既然兩者的功能那麼相近,到底為什麼要有 Reference 的存在呢?針對找到的資訊作一些整理如下:

  • Reference 和 Pointer 在功能和使用上的差異
  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)

C++ 標準並沒有規定 compiler 要怎麼實作 Reference,但是似乎背後還是用指標的方式實現,所以在效能上並無差異。

  • Reference 的存在意義
  1. I believe the key insight into why C++ has reference types as well as pointer types is that reference types enable overloaded operators to look like built-in operators, as well as act like them.
  2. Pointers can do almost everything that references can do, but they can lead to expressions that don't look right. On the other hand, references have some restrictions that make them less convenient than pointers for implementing algorithms and data structures. References reduce, but do not eliminate, the need for pointers.
  3. As a general rule, use references in function parameters and return types to define attractive interfaces. Use pointers to implement algorithms and data structures.

參考資料:

No comments:

Post a Comment