所以我有这样的东西
class baseclass {
....
}
class derived : public baseclass {
...
}
void func(boost::shared_ptr<baseclass>& a){
//stuff
}
boost::shared_ptr<derived> foo;
func(foo);
这行得通吗?我假设不是因为它不是同一种类型,但是我没有能力将它转换为正确的类型,所以有没有你能想到的解决方法可以使这项工作成功?
编辑:据我所知,我无法进行转换的原因是因为我正在对 boost::shared_ptr<derived>
类型的 vector 进行排序所以我只用 vec.begin() 和 vec.end() 调用排序
最佳答案
shared_ptr<T>
can be implicitly converted toshared_ptr<U>
wheneverT*
can be implicitly converted toU*
. In particular,shared_ptr<T>
is implicitly convertible toshared_ptr<T const>
, toshared_ptr<U>
where U is an accessible base ofT
, and toshared_ptr<void>
.
http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#Members
不过,按照您现在的代码,它不会起作用。 boost::shared_ptr<baseclass>
的隐式构造对象必须绑定(bind)到 const 引用,或者被复制以在构造之外持久存在。
考虑一下
void func(boost::shared_ptr<baseclass> a)
或
void func(const boost::shared_ptr<baseclass>& a)
关于c++ - boost shared_ptr 传递派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16922522/