C ++ polymorphism with boost scoped_ptr

Why doesn't the following code allow foo (ptr) to be called?

#include <boost/scoped_ptr.hpp>
struct A {
    virtual ~A() {}

struct B: public A {};

void foo(boost::scoped_ptr<A>& a) {}

void goo(A& a) {}
int main() {
    boost::scoped_ptr<B> ptr(new B);
    B b;


The corresponding form in which we submit the links works as expected. Shouldn't we be doing polymorphism with boost scoped_ptr?

g ++ with boost 1.49 gives me:

error: invalid initialization of reference of type β€˜boost::scoped_ptr<A>&’ from expression of type β€˜boost::scoped_ptr<B>’



source to share

1 answer

This is because foo

it accepts a referenced pointer for some reason. It is completely unnecessary and the reason why the call fails. There is a conversion from scoped_ptr<B>

to scoped_ptr<A>

, but not from scoped_ptr<B>&

to scoped_ptr<A>&


You have to pass it as a const reference.

void foo(boost::scoped_ptr<A> const & a) {}


By the way, this is not a "problem" with smart pointers as such. The following code doesn't work for the same reasons as yours.

void foo(A*& p) {}
int main()
    B* p = new B;
    foo(p); //FAIL


To fix this you have to pass the pointer either by value or, if you are kinky enough, reference const

 void foo (A * const & p); // <-- a perv wrote this




All Articles