boost scoped_ptr的C ++多态性 [英] C++ polymorphism with boost scoped_ptr
问题描述
为什么下列代码不允许调用foo(ptr)?
Why does the following code not 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);
foo(ptr);
B b;
goo(b);
}
我们传递引用的对应表单按预期工作。我们不应该用boost scoped_ptr来做多态性
?
The corresponding form where we pass references works as expected. Are we supposed not to do polymorphism with boost scoped_ptr ?
g ++ with boost 1.49给我:
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>’
推荐答案
这是因为 foo
某些原因,通过引用获取一个作用域指针 。这是完全不必要的,是呼叫失败的原因。有从 scoped_ptr< B>
到 scoped_ptr< A>
的转换,但不是 scoped_ptr< ; B>&
到 scoped_ptr< A>&
。
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>&
.
传递它作为const的引用。
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
}
为了解决这个问题,你必须传递指针值,或者,如果你足够的变态,通过引用const
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
这篇关于boost scoped_ptr的C ++多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!