簡體   English   中英

帶有抽象類的unique_ptr成員和Copy構造函數的Factory Method模式

[英]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中深度復制數據。 有沒有辦法做到這一點? 還是應該改變我的結構? 任何幫助,將不勝感激。

由於要在類層次結構RichDocumentRichApplication配對,因此您應該准備執行以下操作之一:

  • 構建豐富文檔時,請接受任何基本文檔,或者
  • 拒絕所有文檔,但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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM