Search code examples
c++shared-ptr

can't use assignment to construct an object using derived shared_ptr


This is the code. I think it shows my question. So how can I make it work?

#include <memory>

struct base {
  virtual ~base();
};

struct derived : public base {};

struct A {
  A(std::shared_ptr<base> x) {}
};

int main() {
  std::shared_ptr<derived> data = std::make_shared<derived>();
  A a1(data);  // ok
  A a2 = data; // not ok
  return 0;
}

Solution

  • A a2 = data; // not ok
    

    This doesn't work because the compiler would need to perform two conversions (shared_ptr<derived> -> shared_ptr<base> -> A), but it may only do one implicitly.

    To fix it, you can either add an overloaded constructor, if you know derived:

    A(std::shared_ptr<derived> x) : A(static_cast<std::shared_ptr<base>>(x)) {}
    

    or you can store your pointer as shared_ptr<base> to begin with:

    std::shared_ptr<base> data = std::make_shared<derived>();