返回值问题
关于返回值的存活期问题,我最近困了,请同志们帮忙,两个程序如下:
(一):#include<iostream>
using namespace std;
struct sysop
{
char name[20];
char quote[64];
int used;
};
const sysop & use (sysop & sysopref);//function with a reference return type
int main()
{
sysop looper={"rick \"fortran\"looper",
"i'm a goto kind of guy.",
0
};
use (looper);//looper is a type sysop
cout <<"looper :"<<looper.used<<"use(s)\n";
return 0;
}
//use ()returns the reference passed to it
const sysop & use(sysop & sysopref)
{
sysop newguy;
newguy=sysopref;
return newguy;
}
但是上述程序的use却不可用,原因是函数返回一个临时变量(newguy)的引用,函数运行完毕后,它将不复存在;请看(二):
#include<iostream>
using namespace std;
int value(int,int);
int main()
{
int a=3,b=4,c;
c=value(a,b);
cout<<c;
return 0;
}
int value(int a,int b)
{
c=a+b;
return c;
}
但是次程序却得到了结果,我想这两个程序都是在子函数中定义了一个数据,它们都是在调用后被释放了,为什一个可以得到返回值,而另一个却没有得到返回值呢?+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++