关于C++中函数返回值的疑惑

      当初一直以为函数的返回类型若不是返回指针或者引用,那它返回值一定会再次拷贝。

       如:

                  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 :这一行出错,好像该函数的返回值没有存储的空间
}

 

我有点不明白,是不是若函数返回内建类型,则不能是作左值,所以不能取址,而其他自定义类型则可以作左值。那函数调用时和返回值时的堆栈是怎样保存的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值