Summary from answers and links below:
- A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
- A pointer can point to NULL while reference can never point to NULL
- You can't take the address of a reference like you can with pointers
- 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:
- My alltime favorite C++ FQA lite
- References vs. Pointers
- An Introduction to References
- References and const
原文链接: https://www.cnblogs.com/smartvessel/archive/2011/04/18/2019520.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/24209
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!