源代码如下
#include<iostream>
using namespace std;
class T
{
public:
T()
{
cout<<"Constructor called"<<endl;
i=0;
}
T(const T& t)
{
cout<<"Copy called"<<endl;
}
~T()
{
cout<<"Destructor called"<<endl;
}
T& operator=(const T& t)
{
this->i=t.i;
cout<<"= called"<<endl;
return *this;
}
private:
int i;
};
T f(T t)
{
return t;
}
void try1()
{
T t1;
f(t1);
}
void try2()
{
T t2;
T t3=f(t2);
}
void try3()
{
T t4;
T t5;
t5=f(t4);
}
int main()
{
cout<<"try1 start"<<endl;
try1();
cout<<"try1 over"<<endl;
cout<<"try2 start"<<endl;
try2();
cout<<"try2 over"<<endl;
cout<<"try3 start"<<endl;
try3();
cout<<"try3 over"<<endl;
system("pause");
}
运行结果如下:
解释:
void try1() { T t1; // 构造t1 f(t1); // f(t1),拷贝t1给形参t,f在 return 时又将t拷贝作为返回值 } void try2() { T t2; // 构造t2 T t3=f(t2); // f(t2),拷贝t2给形参t,f在 return 时又将t拷贝作为返回值,而这个返回值就是t3 } void try3() { T t4; // 构造t4 T t5; // 构造t4 t5=f(t4); // f(t4),拷贝t4给形参t,f在 return 时又将t拷贝作为返回值,这个返回值并不是t5,因为t5不在这里构造,因此调用= }