打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Gcc 4.7返回对象引用 与返回对象
#include <iostream>

using namespace std;

typedef  unsigned int      DWORD;

class ReturnObject
{
public:
    int i;
    ReturnObject(){ cout << "Constructing " << (DWORD)this<<endl;}
    ReturnObject(const ReturnObject &r){ cout << "Copy " <<(DWORD)this<<'\t'<<(DWORD)&r<<endl;}
     ReturnObject & operator =( const ReturnObject &r){ cout << "Assign " <<(DWORD)this<<'\t'<<(DWORD)&r<<endl;  return *this;}
    ~ReturnObject(){ cout << "Destructing " <<(DWORD)this<<endl;}
};



ReturnObject & test()
{
      ReturnObject b ;
   b.i=1;
   return b;
}

int main(int argc, char *argv[])
{
   ReturnObject  Ga=test();
      cout<<Ga.i<<endl;

    return 0;
}
Constructing 2293164

Destructing 2293164

Copy2293288 2293164

304361816

Destructing 2293288



去掉引用 ,则结果如下:

ReturnObject test()
{
      ReturnObject b ;
   b.i=1;
   return b;
}


Constructing 2293288

1

Destructing 2293288


ReturnObject Ga=test();

ReturnObject Ga;
Ga=test();
差别较大。不考虑优化的情况下。
前者调用一次拷贝构造。
后者调用构造,以及赋值各一次
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
c++ 类的继承与派生
new[]和delete[]为何要配对使用?
关于构造函数中的异常处理
C++函数返回值为对象时,构造析构函数的执行细节
C++和C#中的值传递和引用传递
C 类(深拷贝和浅拷贝)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服