假设我有一个具有抽象类ApplicatonBase的设置,该设置与另一个抽象类DocumentBase:有一个unique_ptr
class ApplicationBase
{
public:
void factoryMethod()
{
_doc->doSomething();
};
protected:
std::unique_ptr<DocumentBase> _doc;
};
class DocumentBase
{
public:
virtual void doSomething() = 0;
};
现在我开发具体的类RichDocument和RichApplication如下:
class RichDocument : public DocumentBase
{
public:
void doSomething() override
{
std::cout << "I'm rich documentn";
}
};
class RichApplication : public ApplicationBase
{
public:
RichApplication()
{
_doc = std::unique_ptr<RichDocument>(new RichDocument());
}
RichApplication(const RichApplication& other)
{
/*
* TODO: I want to copy the data from other document
* unique_ptr and give it to the current document
* unique_ptr
*/
//Following crashes as the copy constructor is not known:
// error: no matching function for call to ‘RichDocument::RichDocument(DocumentBase&)
//_doc.reset(new RichDocument(*other._doc));
}
};
问题出在复制构造函数中。我想在复制构造函数中深度复制unique_ptr中的数据。有办法做到这一点吗?或者我应该改变我的结构?如有任何帮助,我们将不胜感激。
由于要在类层次结构中对RichDocument
和RichApplication
进行配对,因此应准备执行以下操作之一:
- 构造富文档时接受任何基础文档,或者
- 拒绝除
RichDocument
之外的所有文档
假设初始化_doc
的唯一方法是在RichApplication
的构造函数中,第二种方法应该足够好:
RichDocument *otherDoc = dynamic_cast<RichDocument*>(other._doc.get());
// We created RichDocument in the constructor, so the cast must not fail:
assert(otherDoc);
_doc.reset(new RichDocument(*otherDoc));