如何在构造函数中初始化共享指针?

问题描述

我试图将构造函数中其他类的对象初始化为共享指针。我需要一个 shred 指针,因为我需要一个引用以在 ...

中的另一种方法中使用

标题

class MyClass
{
public:
   MyClass() ;
   ~MyClass() {};
   void myMethod();
private:
   std::shared_ptr<dds::pub::Publisher>m_pub;
   std::shared_ptr<dds::domain::DomainParticipant>m_part;
};

cpp

MyClass::MyClass()  
{
  m_part = std::make_shared<dds::domain::DomainParticipant>(domain::default_id());
  m_pub = std::make_shared<dds::pub::Publisher>(m_part);
}
MyClass::myMethod()
{
  //m_part,m_pub are used here 
}

在这里遗漏了什么?

Error   C2039   'delegate': is not a member of 'std::shared_ptr<dds::domain::DomainParticipant>'     

dds::pub::Publisher

namespace dds
{
  namespace pub
  {
     typedef dds::pub::detail::Publisher Publisher;
  }
}

出版商

namespace dds { namespace pub { namespace detail {
typedef 
dds::pub::TPublisher<org::eclipse::cyclonedds::pub::PublisherDelegate> Publisher;
} } }

发布者委托

namespace dds { namespace pub { namespace detail {
    typedef 
dds::pub::TPublisher<org::eclipse::cyclonedds::pub::PublisherDelegate> Publisher;
} } }


class OMG_DDS_API PublisherDelegate : public 
org::eclipse::cyclonedds::core::EntityDelegate
{
public:
typedef ::dds::core::smart_ptr_traits< PublisherDelegate >::ref_type ref_type;
typedef ::dds::core::smart_ptr_traits< PublisherDelegate >::weak_ref_type weak_ref_type;

PublisherDelegate(const dds::domain::DomainParticipant& dp,const dds::pub::qos::PublisherQos& qos,dds::pub::PublisherListener* listener,const dds::core::status::StatusMask& event_mask);

TPublisher

template <typename DELEGATE>
class dds::pub::TPublisher : public dds::core::TEntity<DELEGATE>
{
public:

   typedef dds::pub::PublisherListener                 Listener;

public:
   OMG_DDS_REF_TYPE_PROTECTED_DC(TPublisher,dds::core::TEntity,DELEGATE)
   OMG_DDS_IMPLICIT_REF_BASE(TPublisher)

   TPublisher(const dds::domain::DomainParticipant& dp);

   TPublisher(const dds::domain::DomainParticipant& dp,dds::pub::PublisherListener* listener = NULL,const dds::core::status::StatusMask& mask = dds::core::status::StatusMask::none());

我尝试了答案中给出的方法出现新错误

Error   C2672   'std::dynamic_pointer_cast': no matching overloaded function  in TPublisher.hpp   

解决方法

我想 m_pub 应该像这样初始化

m_pub = std::make_shared<dds::pub::Publisher>(*m_part);

dds::pub::Publisher 又名 dds::pub::TPublisher 的构造函数采用 const dds::domain::DomainParticipant 引用。

问题更新后答案有所改变。