![](/img/trans.png)
[英]Copy constructor for a class with unique_ptr to an abstract class as a member
[英]Factory Method pattern with unique_ptr member of a abstract class and Copy constructor
假設我有一個抽象類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 document\n";
}
};
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.