C++ polymorphism with boost scoped_ptr

怎甘沉沦 提交于 2019-12-04 12:57:07

That's because foo, for some reason, takes a scoped pointer by reference. That is completely unnecessary and is 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 should pass it as reference to const.

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

Incidentally, this isn't a "problem" of smart pointers per se. The following code fails for the same reasons as yours.

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

In order to fix this you have to pass the pointer either by value, or, if you're sufficiently perverted, by reference to const

 void foo (A * const & p); // <-- a perv wrote this
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!