c++ - boost shared_ptr 传递派生类

标签 c++ boost shared-ptr derived-class

所以我有这样的东西

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 to shared_ptr<U> whenever T* can be implicitly converted to U*. In particular, shared_ptr<T> is implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is an accessible base of T, and to shared_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/

相关文章:

c++ - 与 boost::python::extract<obj> 相反

c++ - C++/Qt - 内存分配如何工作?

c++ - 无法将char数组写入Windows注册表项

.select_on_container_copy_construction 左侧的 C++ boost::geometry::index::rtree 必须具有类/结构/union

c++ - 在未安装 visual 的计算机上设置 xll

c++ - 智能指针作为条件 : are if (p) and if (p. get()) 等效?

c++ - 返回 shared_ptr 和异常安全

C++ STL : Using map with priority_queue

c++ - 在共享内存中复制 char* boost

c++ - boost::adaptors::transformed 后跟 boost::adaptors::filtered 调用函数两次