When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
References vs Pointers
Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain.
引用与指针
两个引用和指针可以用来改变一个函数在另一个函数中的局部变量。两者也可以用来保存大对象的复制时作为参数传递给函数传递或者从函数返回,以获得效率增益。
References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers
引用没有指针那么强大
1)引用一旦创建,它不能被以后作出引用另一对象,它不能被重新设置。而用指针可以。
2)引用不能为NULL。指针通常由NULL来表明他们没有指向任何有效的东西。
3)声明引用时必须被初始化。指针没有这样的限制
references in C++ cannot be used for implementing data structures like Linked List, Tree, etc.
C++中的引用不能用来实现像链表,树等数据结构。
References are safer and easier to use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise )
2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.
Reference must be used pass the argument in copy constructor and some operators overloading.
本文详细对比了C++中的引用与指针的区别,包括它们如何改变函数中的局部变量,提高大对象传递效率,以及引用在安全性与使用便捷性上的优势。同时指出引用在某些方面的局限性,如无法用于实现链表、树等数据结构。
1446

被折叠的 条评论
为什么被折叠?



