Search code examples
boostshared-ptrc++03

create boost::shared_ptr with a reference in constructor


I have the following case: the class "B" inherits from class "A". The class "C" has a reference to "A", which is passed to in the constructor. in class "D", I want to use class "C", but I only have a reference to "B". Currently I'm using standard pointers, but i need to migrate to boost::shared_ptr.

class A {...};

class B: public A {...};

class C {
 public:
  C(A& _a)
   : a(_a)
   {...}

 private:
  A& a;
};

class D
{
  private:
   B& b;
   void someFunc()
   {
     C* c1 = new C(b); // Working
     boost::shared_ptr<C> c2 = boost::make_shared<C>(b); // not working: "cannot convert const B in A&" error
   }
};

My Question: How do I need to wrap/cast/derefrence/whatever the instance "b", so that the shared_ptr is created correctly?

With the implementation above I get an "cannot convert const B in A&" error.

Thank you for your support.


Solution

  • Found the solution myself: I need to wrap it in boost::ref, i.e.

    boost::shared_ptr<C> c2 = boost::make_shared<C>(boost::ref(b));