首页 新闻 会员 周边

求老师解释一下C++代码的结果

0
悬赏园豆:20 [已解决问题] 解决于 2013-11-17 03:14

#include <iostream>
using namespace std;
class A
{
public:
A(){cout<<"构造函数运行\n";}
A(A&t){cout<<"拷贝构造函数运行\n";}
~A(){cout<<"析构造函数运行\n";}
};
A func()
{
A aa;
return aa;
}


void main()
{
A a;
A b=func();

}

 

构造函数运行
构造函数运行
拷贝构造函数运行
析构造函数运行
析构造函数运行
析构造函数运行

 

运行结果的拷贝构造函数是那一句所导致的?

是main里面的赋值语句  还是func函数返回aa时的副本?

若果A b=func();改成func();结果一致。

说明A b=func();赋值时没有调用拷贝构造函数,那么为什么将其换成简单的A b=a;会有拷贝构造函数?

浩荡乾坤的主页 浩荡乾坤 | 初学一级 | 园豆:135
提问于:2013-11-14 20:45
< >
分享
最佳答案
0

return aa;这一句会产生拷贝构造函数,用来构造返回值。

A b=a;这句也会产生拷贝构造函数,用来构造b这个对象。

A b=func(),这句可能产生额外的拷贝构造,也可能不产生。因为func()的返回的临时变量可以被优化掉,在return的时候直接就构造b.这是视具体编译器的实现。

 

在C++标准中对于这个的论述如下,有兴趣就看看吧。

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object,
even if the copy constructor and/or destructor for the object have side effects. In such cases, the implementation
treats the source and target of the omitted copy operation as simply two different ways of referring to
the same object, and the destruction of that object occurs at the later of the times when the two objects
would have been destroyed without the optimization. 111) This elision of copy operations is permitted in the
following circumstances (which may be combined to eliminate multiple copies):
— in a return statement in a function with a class return type, when the expression is the name of a
non-volatile automatic object with the same cv-unqualified type as the function return type, the copy
operation can be omitted by constructing the automatic object directly into the function’s return value
— when a temporary class object that has not been bound to a reference (12.2) would be copied to a class
object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary
object directly into the target of the omitted copy
[Example:
class Thing {
public:
Thing();
˜Thing();
Thing(const Thing&);
};
Thing f() {
Thing t;
return t;
}
Thing t2 = f();
Here the criteria for elision can be combined to eliminate two calls to the copy constructor of class Thing:
the copying of the local automatic object t into the temporary object for the return value of function f()
and the copying of that temporary object into object t2. Effectively, the construction of the local object t
can be viewed as directly initializing the global object t2, and that object’s destruction will occur at program
exit. —end example]
收获园豆:20
嗷嗷 | 小虾三级 |园豆:757 | 2013-11-15 09:23

谢谢您的回答!很专业!!

浩荡乾坤 | 园豆:135 (初学一级) | 2013-11-15 13:48
其他回答(1)
0

赋值运算符会产生“拷贝”的效果

飞鸟_Asuka | 园豆:209 (菜鸟二级) | 2013-11-15 09:52
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册