C ++多态性与提升的scoped_ptr [英] C++ polymorphism with boost scoped_ptr
问题描述
为什么以下code不允许美孚(PTR)被称为?
的#include<升压/ scoped_ptr.hpp>
结构A {
虚拟〜A(){}
};结构A:公开发行A {};无效美孚(提高:: scoped_ptr的< A>&安培; A){}无效咕(A和一个){}
诠释主(){
提高:: scoped_ptr的< B> PTR(新B);
富(PTR);
B B;
咕(B);
}
在这里我们通过引用相应的形式按预期工作。难道我们不应该做的多态性
与升压scoped_ptr的?
G ++与提升1.49给我:
错误:类型的引用无效初始化的boost :: scoped_ptr的< A>&放大器;从类型前pression'的boost :: scoped_ptr的< B>'
这是因为富
,由于某些原因,需要一个作用域指针的引用。这是完全没有必要的,这就是为什么调用失败的原因。有一个从转换的scoped_ptr< B>
到的scoped_ptr< A>
而不是从的scoped_ptr&LT ; B>&安培;
到的scoped_ptr< A>&安培;
您应该把它作为参考常量。
无效美孚(提高:: scoped_ptr的< A>常量和放大器;一){}
顺便说一句,这不是一个智能指针本身的问题。下面code失败出于同样的原因是你的了。
无效美孚(A *安培; P){}
诠释的main()
{
B * P =新型B;
富(P); //失败
}
为了解决这个问题,你要么按值传递指针,或者,如果你足够变态,通过引用为const
无效美孚(A * const的&安培; P); //< - 一个PERV写了这
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);
}
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 gives me:
error: invalid initialization of reference of type ‘boost::scoped_ptr<A>&’ from expression of type ‘boost::scoped_ptr<B>’
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
这篇关于C ++多态性与提升的scoped_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!