class WithCC {
public:
WithCC() {}
WithCC(const WithCC&) {
cout << "in WithCC's copy constructor" << endl;
}
};
class Composite {
WithCC withcc; // Embedded objects
public:
Composite() {}
};
int main() {
Composite c;
Composite c2 = c;
}
使用上面的代码,withcc 的复制构造函数被调用,我得到输出: 在 WithCC 的复制构造函数中
但是如果我像这样向 Composite 添加复制构造函数...
class Composite {
WithCC withcc; // Embedded objects
public:
Composite() {}
Composite(const Composite&) {
cout << "in composite's copy constructor" << endl;
}
};
withcc 的复制构造函数似乎没有被调用,因为输出是: 在复合体的复制构造函数中
为什么这里没有调用 withcc 的复制构造函数?
最佳答案
在第一个示例中,您省略了 Composite
的复制构造函数,因此 C++ 为您生成了一个默认构造函数。这个默认的本质上是逐个字段复制运行,因此运行 WithCC
的复制构造函数。
当您显式定义复制构造函数时,C++ 并没有什么魔力。您可以根据需要复制这些字段。例如
Composite(const Composite& other) : withcc(other.withcc) {
cout << "in composite's copy constructor" << endl;
}
关于c++ - 关于何时调用嵌入对象的复制构造函数的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21198895/