- 论坛徽章:
- 0
|
问题1:
函数按值返回一个类对象时候,如果是形参,为什么还要自我复制一遍?而局部变量就不用
. 写个测试程序:
class X{
public:
X(int m):s(m){}
X(const X& ;
~X(){ cout <<"erase an object,s ="<<s<<endl;}
X& operator =(const X& );
int s;
};
X::X(const X & x){
this->s = x.s+1;
cout <<"CP fun,s1="<<this->s<<"s2="<<x.s<<endl;}
X::X& X: perator =(const X& x){
s=x.s;
cout<<"in an operatot,s1 ="<<this->s<<"s2="<<x.s<<endl;
return *this;}
X f(X x)
{
X a(0);
cout <<"call a func with para X object\n";
return x;
}
int main()
{
X a(1);
a=f(a);
cout<<"returned in main()\n";
}
输出:
CP fun,s1=2s2=1
call a func with para X object
CP fun,s1=3s2=2
erase an object,s =0
in an operatot,s1 =3s2=3
erase an object,s =3
erase an object,s =2
returned in main()
erase an object,s =3
为什么在return x之前,还要创建一个拷贝?而且这个拷贝烤完之后立马析构,既然这样为
什么不干脆直接用原来的呢?它们的生存期是一样的吧
问题2:
还是上面那个程序,只main改为
int main()
{
X a(1);
X b=f(a);
cout<<"returned in main()\n";
}
按理说应该调用拷贝构造函数初始化b的,可是结果是:
CP fun,s1=2s2=1
call a func with para X object
CP fun,s1=3s2=2
erase an object,s =0
erase an object,s =2
returned in main()
erase an object,s =3
erase an object,s =1
还有第三个问题...
就是把=的返回值从引用返回改为按值返回.运行结果:
CP fun,s1=2s2=1
call a func with para X object
CP fun,s1=3s2=2
erase an object,s =0
in an operatot,s1 =1s2=3
CP fun,s1=4s2=3
erase an object,s =4
erase an object,s =3
erase an object,s =2
returned in main()
erase an object,s =3
可见return *this;前又拷贝了一个临时对象,但是它立马被析构,并且返回的还是旧值.这又何必创建呢?
请大家帮我看看吧,谢谢了!!!! |
|