C++中拷贝构造函数调用时机通常有三种情况
- 使用该类的一个已经创建完毕的对象来初始化该类的一个新对象
- 值传递的方式给函数参数传值(即函数的形参是类的对象)
- 以值方式返回局部对象(即函数的返回值是类的对象)
具体的理解如下:用代码说明
- 情况一:
#includeusing namespace std; class Person { public: Person() { cout << "调用无参构造函数" << endl; } Person(int age) { m_age = age; cout << "调用有参构造函数" << endl; } Person(const person& p) { m_age = p.m_age; cout << "调用拷贝构造函数" << endl; } ~Person() { cout << "调用析构函数" << endl; } int m_age; }; void test01() { Person p1(10); person p2(p1); } int main() { test01(); return 0; }
此情况为最常用情况,可以使用输入法可以使用代入法。
- 情况2:
#includeusing namespace std; class Person { public: Person() { cout << "调用无参构造函数" << endl; } Person(int age) { m_age = age; cout << "调用有参构造函数" << endl; } Person(const person& p) { m_age = p.m_age; cout << "调用拷贝构造函数" << endl; } ~Person() { cout << "调用析构函数" << endl; } int m_age; }; void doWork(Person p1){} void test02() { Person p; doWork(p); } int main() { test02(); return 0; }
图中:doWork(p)中的p是通过上边Person类创建的对象p,是实参,调用doWork 函数时,void doWork(Person p)中的p是通过拷贝构造函数复制的临时的,二者不是一个东西。
- 情况3:
#includeusing namespace std; class Person { public: Person() { cout << "调用无参构造函数" << endl; } Person(int age) { m_age = age; cout << "调用有参构造函数" << endl; } Person(const person& p) { m_age = p.m_age; cout << "调用拷贝构造函数" << endl; } ~Person() { cout << "调用析构函数" << endl; } int m_age; }; void doWork2() { Person p1; return p1; } void test03() { Person p=doWork2(); } int main() { test03(); return 0; }
图中:通过默认构造返回p1,而且是一个局部对象,以值的形式返回局部对象,不会直接返回p1这个对象,会调用拷贝构造把p1拷贝一个新的对象返回给外边,所以p和p1不是一个东西,p是通过拷贝构造复制的p1。



