簡體   English   中英

在C ++中將shared_ptr返回給基類

[英]Return a shared_ptr to the base class in C++

我有以下問題。 我有一堂課,有功能

std::shared_ptr<IBaseInterface> getBaseInterface()
   {
      return m_spBase;
   }

我也有以下內容:

private:

   std::shared_ptr<IBaseInterface> m_spBase;

   XMLReader* m_xmlReader;

   std::unique_ptr<DerivedInterface> m_xmlInterface;

這里的事情是DerivedInterface繼承自IBaseInterface ,因此從外部看,它應該作為IBaseInterface可見。 我還應該提到,m_xmlInterface在這里不必是一個指針(唯一/不唯一)。 同樣,DerivedInterface是一個具體的類,它具有以下構造函數(這對我的問題可能不太重要):

   DerivedInterface( XMLReader* pxmlReader );

IBaseInterface只是一個純抽象類,它具有DerivedInterface定義的一些純虛函數。

現在,我想創建一個DerivedInterface實例,並使用getBaseInterface將其作為IBaseInterface返回,這是我的主要觀點。 我嘗試在類的構造函數中執行以下操作:

m_xmlInterface = std::unique_ptr<DerivedInterface>(
     new DerivedInterface( m_xmlReader ) );

  m_spBase = std::move( m_xmlInterface );

但這是行不通的(我假設您不能將一種類型的指針移到另一種類型,即使一個指針指向的類繼承自另一種)。 如果有人提出任何建議,我將很高興。

考慮一下您想要實現的所有權語義,並首先向類和函數的用戶發布廣告,然后選擇適合的實現和類型。

  1. 從您編寫的內容看來,您似乎想在類的對象和它的用戶之間共享m_xmlInterface所有權。 這意味着,如果用戶獲得了該接口,則當您的類的對象消失時,它仍然擁有該接口。 在這種情況下,您應該將其存儲為類中的共享指針,並將其也返回為共享指針。 在這種情況下,您將擁有:

     std::shared_ptr<DerivedInterface> m_xmlInterface; 

    和:簡單地:

     std::shared_ptr<IBaseInterface> getBaseInterface() { return m_xmlInterface; } 

    無需通過另一個變量。 這是顯示此工作的完整示例:

     #include <memory> struct A {}; struct B : public A {}; class Foo { public: Foo() {} std::shared_ptr<A> get() { return mB; } private: std::shared_ptr<B> mB; }; int main() { auto foo = Foo{}; auto a = foo.get(); } 
  2. 如果您希望所有權嚴格屬於您的類,則可以將其存儲為unique_ptr 然后,授予訪問權限的唯一方法是返回原始指針或引用(可能更可取),除非您希望使類放棄所有權(在這種情況下,應使用move 因此,最好不要返回共享指針,而是返回唯一的指針,這使調用者可以自由決定自己是否想要在以后共享它。 在這種情況下,您將擁有:

     std::unique_ptr<DerivedInterface> m_xmlInterface; 

    和:

     std::unique_ptr<IBaseInterface> getBaseInterface() { return std::move(m_xmlInterface); } 

    但是請注意,任何人調用此函數后,您的類都無法再使用m_xmlInterface ,它將失去對它的所有所有權。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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