您的位置:首页 > 其它

关于g++中拷贝构造函数被优化的情况

2014-06-05 16:59 120 查看
参阅如下代码:

cat t1.cpp
#include <iostream>
#include <cstdio>
using namespace std;

class A{
public:
A(int _i,int _j){
cout<<"con 2"<<endl;
i = _i;
j = _j;
a = 999;
};
A(const A& a){
cout<<"copy"<<endl;
this->i = a.i;
this->a = a.j;
this->j = 888;
};
~A(){
cout<<"d"<<endl;
};
A& operator=(const A& other){
cout<<"in operator"<<endl;
this->i = other.i;
this->a = other.j;
this->j = 777;
return *this;
}
int i;
int a;
int j;
};
A f()
{
A i(1,2);
printf("in f():i addr is =%x\n",&i);
return i;
}

int main()
{
A b = f();
printf("in main():b addr is =%x====i=%d====j=%d=====a=%d\n",&b,b.i,b.j,b.a);
}


编译运行后发现如下问题:

1,f()函数返回时的拷贝构造函数没有调用,导致main()函数中的b对象没有得到预期值;

2,打印f()函数中的对象i和main()函数中的对象b,发现地址一致;说明整个程序中只产生了一个对象。

con 2
in f():i addr is =796bb0
in main():b addr is =796bb0====i=1====j=2=====a=999
d


经过查阅网络资料,发现 http://bbs.csdn.net/topics/390542033 帖子也遇到了同样的问题,并给出了答案,由于优化的原因,导致了函数f()的返回值被放到了调用方main中。

看看多个变量从f()中生成的情况,事实上变量都是在main()中:

#include <iostream>
#include <cstdio>
using namespace std;

class A{
public:
A(int _i,int _j){
cout<<"con 2"<<endl;
i = _i;
j = _j;
a = 999;
};
A(const A& a){
cout<<"copy"<<endl;
this->i = a.i;
this->a = a.j;
this->j = 888;
};
~A(){
cout<<"d"<<endl;
};
A& operator=(const A& other){
cout<<"in operator"<<endl;
this->i = other.i;
this->a = other.j;
this->j = 777;
return *this;
}
int i;
int a;
int j;
};
A f()
{
A i(1,2);
printf("in f():i addr is =%x\n",&i);
return i;
}

A call_f()
{
A c = f();
printf("in caller ():c addr is =%x\n",&c);
return c;
}

int main()
{
int i;
A a = call_f();
A b = f();
A c = f();
printf("in main() i addr is %x\n",&i);
printf("in main():a addr is =%x====i=%d====j=%d=====a=%d\n",&a,a.i,a.j,a.a);
printf("in main():b addr is =%x====i=%d====j=%d=====a=%d\n",&b,b.i,b.j,b.a);
printf("in main():c addr is =%x====i=%d====j=%d=====a=%d\n",&c,c.i,c.j,c.a);

}

./a.out
con 2
in f():i addr is =d774aae0
in caller ():c addr is =d774aae0
con 2
in f():i addr is =d774aad0
con 2
in f():i addr is =d774aac0
in main() i addr is d774aaec
in main():a addr is =d774aae0====i=1====j=2=====a=999
in main():b addr is =d774aad0====i=1====j=2=====a=999
in main():c addr is =d774aac0====i=1====j=2=====a=999
d
d
d
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: