当初一直以为函数的返回类型若不是返回指针或者引用,那它返回值一定会再次拷贝。
如:
double func()
{
double temp;
return temp; //若是以前,我会认为这是返回temp的副本
}
今天无意中写了一个类,发现函数返回值 有所不同。我特地写了一个程序进行了实验,程序如下:
/*
*这程序能说明string代表的类类型返回的是一定空间的数据,而 int 类型的则不会,好像直接返回值了
*这也会说明一个有趣的问题:若返回一个局部string对象,则直接返回该对象(也就是说返回的地址与原先的局部对象的空间是同一位置)。
*若函数返回是一个string的引用,则看是函数的返回类型是引用还是string的类型了
*/
#include <iostream>
#include <string>
using namespace std;
string test()
{
string i ;
cout <<"test(): " << &i << endl;
return i;
}
string test2()
{
string i;
string &a = i;
cout << &i << endl;
cout << "test2() " << &a << endl;
return i;
}
string &test3()
{
string i = "hello ";
string &a = i;
cout << "test3(): "<< &i << endl;
cout << a << " " << &a << endl;
return a;
}
int test1()
{
int i ;
cout << "test1(): " << &i << endl;
return i;
}
int main()
{
cout << "test(): " << &(test()) << endl; //与test()中的地址一样
cout << "test2(): " << &(test2()) << endl; //因为返回的是test2()中的一个局部string的对象
//的引用,则两者的地址不同了
cout << &b << endl;
string &a = test3();
cout << &a << endl; //将test3()中绑定给非const的引用发现两者地址一样
//cout << &(test1()) << endl; // error :这一行出错,好像该函数的返回值没有存储的空间
}
我有点不明白,是不是若函数返回内建类型,则不能是作左值,所以不能取址,而其他自定义类型则可以作左值。那函数调用时和返回值时的堆栈是怎样保存的 ?