1 题目实例
class Date
{
public:
Date(int year, int minute, int day)
{
cout << "Date(int,int,int):" << this << endl;
}
Date(const Date& d)
{
cout << "Date(const Date& d):" << this << endl;
}
~Date()
{
cout << "~Date():" << this << endl;
}
private:
int _year;
int _month;
int _day;
};
Date Test(Date d)
{
Date temp(d);
return temp;
}
int main()
{
Date d1(2022, 1, 13);
Test(d1);
return 0;
}
2 结果分析
Date(int,int,int):00D3FE6C
Date(const Date& d):00D3FD5C
Date(const Date& d):00D3FD30
Date(const Date& d):00D3FD8C
~Date():00D3FD30
~Date():00D3FD5C
~Date():00D3FD8C
~Date():00D3FE6C
执行过程
-
创建对象
d1
:Date d1(2022, 1, 13);
输出:
Date(int,int,int):00D3FE6C
-
调用函数
Test
:Test(d1);
-
传递参数
d1
时,调用拷贝构造函数:Date(const Date& d)
输出:
Date(const Date& d):00D3FD5C
-
在
Test
函数内部,创建临时对象temp
,再次调用拷贝构造函数:Date temp(d);
输出:
Date(const Date& d):00D3FD30
-
返回
temp
时,调用拷贝构造函数:return temp;
输出:
Date(const Date& d):00D3FD8C
-
-
析构函数调用:
-
temp
在Test
函数结束时被销毁:~Date()
输出:
~Date():00D3FD30
-
传递给
Test
函数的临时对象d被销毁:~Date()
输出:
~Date():00D3FD5C
-
Test
函数返回创建的临时对象被销毁:~Date()
输出:
~Date():00D3FD8C
-
最后,
d1
被销毁:~Date()
输出:
~Date():00D3FE6C
-
总结
通过这个例子,我们可以看到拷贝构造函数在对象传递和返回时的调用情况,以及对象生命周期结束时析构函数的调用顺序。这有助于理解对象的内存管理和生命周期。