我需要编写一个复制构造函数来深度复制 std::shared_ptr
的内容。但是,类中还定义了一堆变量 int a, b, c, d, e;
。有没有办法在我的新重载代码中生成默认复制构造函数代码(或调用默认复制构造函数)。
这是一个带有注释的代码片段,希望能澄清问题。
class Foo {
public:
Foo() {}
Foo(Foo const & other);
...
private:
int a, b, c, d, e;
std::shared_ptr<Bla> p;
};
Foo::Foo(Foo const & other) {
p.reset(new Bla(*other.p));
// Can I avoid having to write the default copy constructor code below
a = other.a;
b = other.b;
c = other.c;
d = other.d;
e = other.e;
}
最佳答案
我一直认为像这样的问题应该至少有一个标准的答案引述给 future 的读者,所以就在这里。
标准的 §12.8.4 指出:
If the class definition does not explicitly declare a copy constructor, one is declared implicitly.
这意味着当类定义确实显式声明一个复制构造函数时,不会隐式声明一个。所以如果你显式声明一个,隐式的一个不存在,所以你不能调用它。
关于c++ - 从重载的复制构造函数中调用默认复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7297024/