复制构造函数的 2 种不同类型的构造函数调用
考虑下面的示例代码:
#include <iostream>
using namespace std;
class core
{
public:
core(const core& obj)
{
cout << "core copy ctor called\n";
}
core()
{
cout << "core default ctor called\n";
}
};
class sample : public core
{
public:
sample()
{
cout << "sample default ctor called\n";
}
#if 0
sample(const sample& obj)
{
cout << "sample copy ctor called\n";
}
#endif
};
int main()
{
sample s1;
sample s2 = s1; //Line1
return 0;
}
Type1:未为类sample显式声明复制构造函数
(Type1如上面的代码所示。然后类sample的复制构造函数由编译器隐式生成)。 当执行Line1
语句时,首先调用class core
的复制构造函数,然后调用class example
的复制构造函数。
类型2:复制为类示例显式定义的构造函数
当执行Line1
语句时,首先调用class core
的默认构造函数,然后调用class example
的复制构造函数。
问题:
为什么 Type1 和 Type2 中提到的复制构造函数的行为存在差异?
Consider the sample code below:
#include <iostream>
using namespace std;
class core
{
public:
core(const core& obj)
{
cout << "core copy ctor called\n";
}
core()
{
cout << "core default ctor called\n";
}
};
class sample : public core
{
public:
sample()
{
cout << "sample default ctor called\n";
}
#if 0
sample(const sample& obj)
{
cout << "sample copy ctor called\n";
}
#endif
};
int main()
{
sample s1;
sample s2 = s1; //Line1
return 0;
}
Type1: Copy constructor not declared explicitly for class sample
(Type1 is shown in the code above. Then the copy constructor of class sample is implicitly generated by the compiler).
When the statement, Line1
is executed, first the copy constructor of class core
is invoked, and then the copy constructor of class sample
is invoked.
Type2: Copy constructor defined explicitly for class sample
When the statement, Line1
is executed, first the default constructor of class core
is invoked, and then the copy constructor of class sample
is invoked.
Question:
Why is this difference in behavior for copy constructor as mentioned in Type1 and Type2 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您为
sample
显式定义的复制构造函数不会要求调用core
的复制构造函数。如果你想实现这一点,你必须编写: core(obj)
。换句话说,当您编写显式复制构造函数时,您将负责
sample
的复制构造,包括其core
子对象。通过按照您所做的方式编写它,您选择不使用obj
初始化core
子对象。由于您没有说明您希望如何初始化它,编译器仅使用 core 的默认构造函数,因此您概述了第二种情况的行为。相比之下,在第一种情况下,编译器为
sample
生成的默认复制构造函数确实要求使用core
初始化core
子对象> 的复制构造函数,因此观察到的行为。Because the copy constructor you explicitly define for
sample
doesn't ask forcore
's copy constructor to be invoked. You'd have to write: core(obj)
if you wanted to make that happen.Put another way, when you write an explicit copy constructor, you are taking charge of the copy construction of
sample
, including itscore
sub-object. By writing it the way you have done, you have chosen not to initialise thecore
sub-object usingobj
. Since you haven't said how you do want it initialised, the compiler just usescore
's default constructor instead, hence the behaviour in the second case you outline.By contrast, in the first case, the compiler-generated default copy constructor for
sample
does ask for thecore
sub-object to be initialised usingcore
's copy constructor, hence the observed behaviour.