求助关于C++构造函数的疑问

汪瑜彬 2014-03-08 11:19:21
#include<iostream>
using namespace std;
class A
{
public:
A():m(10)
{
cout<<"constuctor A is called!"<<endl;

}
int m;
};
A fun(A a)
{
cout<<"fun &a="<<&a<<endl;

return a;

}
int main()
{
A a;
a=fun(a);
cout<<"main &a="<<&a<<endl;

}
运行结果:
constuctor A is called!
fun &a=0012FF28;
main &a=0012FF7C
疑问1:
上述程序似乎为什么产生了两个对象,却只调用了一次构造函数?
疑问2:
上述程序应该产生了三个对象,1、执行语句 A a
2、用a对象初始化fun中的形参;
3、返回 fun 中局部对象 a时 应该会产生 一个临时对象
对于上述疑问,恳请高手解答,感激不尽!
...全文
193 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
汪瑜彬 2014-03-08
  • 打赏
  • 举报
回复
引用 1 楼 mougaidong 的回复:
要点提示: 1. 复制构造函数 2. RVO
一语道破,谢了
汪瑜彬 2014-03-08
  • 打赏
  • 举报
回复
引用 2 楼 Automation_dmu 的回复:
 class A
 {
 public:
 A():m(10)
 {
 cout<<"constuctor A is called!"<<endl;
 }
 A(const A&){cout<< "A(const A&)" <<endl;}
 A& operator =(const A&) {cout<< "operator =(const A&)" <<endl;return *this;}
 int m;
 };
将A类改成这样,你就明白了!
哦,调用的是默认的复制构造函数 谢谢Automation_dmu
AndyStevens 2014-03-08
  • 打赏
  • 举报
回复
 class A
 {
 public:
 A():m(10)
 {
 cout<<"constuctor A is called!"<<endl;
 }
 A(const A&){cout<< "A(const A&)" <<endl;}
 A& operator =(const A&) {cout<< "operator =(const A&)" <<endl;return *this;}
 int m;
 };
将A类改成这样,你就明白了!
turing-complete 2014-03-08
  • 打赏
  • 举报
回复
要点提示: 1. 复制构造函数 2. RVO

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧