c++ 返回值为 类的对象 http://blog.csdn.net/zyearn/article/details/9709041
2015-06-20 19:28
465 查看
C++中用函数返回值初始类对象时的一个问题
分类: C/C++2013-08-0123:32 1635人阅读 评论(1) 收藏 举报
问题:
有一个类,名字是C,假设有一个函数,它的定义为:
[cpp] view
plaincopy
C func()
{
C tmp;
return tmp;
}
即返回C类型的函数,那么考虑表达式C newC = func();将调用几次构造函数?分别是什么类型的构造函数?
解答:
<<C++ primer>>里有提到这个过程,首先会创建一个临时的类对象,该对象是由复制构造函数生成,参数是tmp。然后再调用复制构造函数初始化newC。所以一共调用了两次复制构造函数。
但现在的gcc不这么处理,会做一个优化。在C函数里有个tmp变量,离开func时不撤销这个对象,而是让newC和这个对象关联起来。也就是说tmp的地址和newC是一样的。
实验:
[cpp] view
plaincopy
#include <iostream>
using namespace std;
class test
{
private:
int num;
static int total ;
public:
test()
{
num = 0 ;
cout << "in the default constructor\n" ;
total ++;
}
test(const test& a )
{
num = a. num;
cout << "in the copy constructor\n" ;
total ++;
}
test(int a)
{
num = a;
cout << "in the one-para constructor\n" ;
total ++;
}
test& operator=(const test& a )
{
num = a. num;
cout << "in the assign op\n" ;
return * this;
}
static void print ()
{
cout << total << endl;
}
int showa ()
{
return num;
}
};
int test:: total = 0;
test testfunc(test t )
{
cout << "1\n";
test tmp(5 );
cout << "address of tmp:" << &tmp << endl ;
cout << "2\n";
return tmp ;
}
int main()
{
test para;
test result = testfunc (para);
cout << "address of result:" << &result << endl ;
cout << "result.a = " << result.showa () << endl;
cout << "3\n";
test::print ();
return 0;
}
那个static变量用来记录一共调用了几次构造函数。
结果:
解释:
第1行是因为test para;调用了默认构造函数。
第2行是因为把para传给函数形参调用了赋值构造函数。
第3行表明进入了testfunc()
第4行tmp调用参数为int的构造函数
第5行输出tmp的地址
第6行表明要离开函数
第7行输出result的地址,发现和tmp的地址是一样的
相关文章推荐
- hdu - 1151 Air Raid(有向无环图的最小路径覆盖)
- http://www.aichengxu.com/view/14872
- assign, retain, copy, weak, strong
- 问题:Bringing up interface eth0: Device eth0 does not seem to be present,delaying initialization. [FAILED]—— 找不到网卡。
- 10 responsibility chain
- 杭电1302 The Snail
- 杭电 ACM HDU Train Problem I
- LeetCode:Container With Most Water 算法题详解
- 1.MyBaits 3.2 简介
- 十大经典数据挖掘算法(9) 朴素贝叶斯分类器 Naive Bayes
- RAID0 RAID1 RAID3 RAID5 RAID6 RAID10 RAID50概念详解
- Exchange发送邮件后卡在草稿箱
- error: server certificate verification failed 解决方案
- Algorithms—42.Trapping Rain Water
- AlphaMobileControls 控件的使用 AlphaImageButton
- 偶尔转帖:AI会议的总结(by南大周志华)
- MonkyTalk学习-6-Verify-WaitFor & WaitForNot
- pthread_cond_wait
- grails domain里面beforeinsert无效
- MacBook Air 安装 Ubuntu 双系统