c++的引用类型一般使用于参数列表中,引用类型的使用很广泛,但是也有它的局限性,在这种情况,则不应该使用引用
#include <iostream>
#include<hf.h>
#include<b.h>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
template <typename elemtype>
elemtype *find1( elemtype*a,int bian, elemtype &value){
if(!a||bian<1)return 0;
for(int ix=0;ix<bian;++ix,++a)
if(*a==value)
return a;
return 0;
}
int main()
{ int a[4]={10,1,5,3};
int c=10;
cout<<find1(a,4,10)<<endl;//这句是错的,视为情况一
cout<<find1(a,4,c)<<endl;//这句是对的,视为情况二
cout<<a;
return 0;
}
上面我写了一个泛型算法,算法的的功能是在数组中找寻一个特定值,并且返回它的指针。
为什么情况一是错误的呢,因为这个函数在调用的时候它传入了一个local object ,在函数结束之后,这个object就挂掉了。此时的引用指向了一个已经死亡的对象,这明显是不合理的。情况二则反之,是正确的。这里给了我一个提醒,引用应该写在合适的地方