引用常常被用做函数的参数,使得被调用函数中的参数名成为调用函数中的变量的别名。
这种传递参数的方法称为按引用传递(pass by reference)。
按引用传递容许被调用的函数访问(读写)调用函数中的变量。
void foo(int* ptr); //按值传递(pass by value) int a; int* pValue = &a; foo(pValue);
其中,pValue的值不能被函数foo改变,即pValue指向a。 可是若是是
void foo(int*& ptr); //按引用传递(pass by reference) void foo(int*& ptr) { ptr = NULL; }
调用事后,pValue就变成了NULL。而第一种状况下pValue不能被改变。
引用是C++的重要特性之一,在大多数状况下避免了使用指针。在C++中,引用不可凭空捏造,由于引用是目标变量的别名。
上述foo函数要用C来实现,则要用指针的指针:
void foo(int** pptr) { *pptr = NULL; }
调用时要foo(&pValue) 这种技术不少用在好比定义一个安全删除引用的函数。所谓安全,就是只有当引用不为空的时候才执行删除, 删除以后,马上把引用赋值为NULL。
template<typename T> inline safe_delete(T*& ptr) { if (ptr) { delete ptr; ptr = NULL; } }
在C++中,应尽可能避免使用指针。
示例一html
#include <iostream> #include <string> void foo(int*& ptr){ ptr = NULL; } int main() { //printf("Hello, World!\n"); int a = 1; int* pValue = &a; printf("a=%d\n",a); printf("pValue=%p\n",pValue); foo(pValue); printf("a=%d\n",a); printf("pValue=%p\n",pValue); return 0; } /** OUTPUT a=1 pValue=0x7a5731c9cddc a=1 pValue=(nil) **/
示例二ios
#include <stdio.h> void foo(int** pptr){ *pptr = NULL; } int main() { //printf("Hello, World!\n"); int a = 1; int* pValue = &a; printf("a=%d\n",a); printf("pValue=%p\n",pValue); foo(&pValue); printf("a=%d\n",a); printf("pValue=%p\n",pValue); return 0; } /* OUTPUT: a=1 pValue=0x7fff80e16a7c a=1 pValue=(nil) */
参考博文安全