#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Date
{
public:
Date()
{
cout<<"Date()"<<endl;
}
Date(const Date& d)
{
cout<<"Date(const Date& d)"<<endl;
}
Date& operator =(const Date& d)
{
cout<<"Date& operator =(const Date& d)"<<endl;
return *this;
}
~Date()
{
cout<<"~Date()"<<endl;
}
};
参数传值和传引用
void fun1(Date d)
{
;
}
void fun2(Date& d)
{
;
}
返回值用传值和传引用
Date fun3()
{
Date d;
return d;
}
Date& fun4()
{
Date d;
return d;
}
临时返回值传值和传引用
Date fun5()
{
return Date();
}
Date& fun6()
{
return Date();
}
测试代码
int main()
{
Date d1;
fun1(d1);
fun2(d1);
Date d3 = fun3();
Date d4 = fun4();
Date d5;
d5 = fun5();
//Date d5 = fun5();
Date d6;
d6 = fun6();
//Date d6 = fun6();
return 0;
}
通过调试以上代码可得:
- 当拷贝构造的临时变量再调用拷贝构造函数和构造对象时,只调用一次拷贝构造函数。
- 当临时变量作返回值再拷贝构造新对象时,只调用一次构造函数
结论:在一个表达式中系统会优化。
#include <iostream>
using namespace std;
class AA
{
public:
AA()
{
cout<<"AA()"<<endl;
}
AA(const AA& d)
{
cout<<"AA(const AA& d)"<<endl;
}
AA& operator =(const AA& d)
{
cout<<"AA& operator =(const AA& d)"<<endl;
return *this;
}
~AA()
{
cout<<"~AA()"<<endl;
}
};
AA f(AA a)
{
return a ;
}
void Test1 ()
{
AA a1 ;
a1 = f(a1);
}
void Test2 ()
{
AA a1 ;
AA a2 = f(a1);
}
void Test3 ()
{
AA a1 ;
AA a2 = f(f(a1));
}
int main()
{
Test1();
Test2();
Test3();
return 0;
}
Test1中调用了 2 次AA的拷贝构造函数, 1 次AA的赋值运算符函数的重载。
Test2中调用了 2 次AA的拷贝构造函数, 0 次AA的赋值运算符函数的重载。
Test3中调用了 3 次AA的拷贝构造函数, 0 次AA的赋值运算符函数的重载。
(f(a1)的返回值作为f()的参数只调用一次拷贝构造函数,函数f(f(a1))的返回值拷贝构造出临时变量和创建对象a2只调用一次拷贝构造即可完成)