【发布时间】:2011-09-04 02:17:57
【问题描述】:
我需要编写一个复制构造函数来深度复制std::shared_ptr 的内容。但是,类中还定义了一堆变量int a, b, c, d, e;。有没有办法在我的新重载代码中生成默认的复制构造函数代码(或调用默认的复制构造函数)。
这是一个带有注释的代码 sn-p,希望能澄清问题。
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;
}
【问题讨论】:
-
为什么需要深拷贝一个shared指针?它的全部目的不就是共享一个公共资源吗?如果您拥有唯一所有权,请考虑使用
unique_ptr。 -
因为 Foo 的每个实例都需要一个
shared_ptr来传递给其他几个类。 -
上述代码中的“...”为
p提供了一个公共接口。
标签: c++ constructor shared-ptr copy-constructor deep-copy