溯造型的shared_ptr<基地以及GT;对于shared_ptr<衍生GT ;? [英] Downcasting shared_ptr<Base> to shared_ptr<Derived>?

查看:84
本文介绍了溯造型的shared_ptr<基地以及GT;对于shared_ptr<衍生GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:在这个例子中,shared_ptr的是像在加速,但它不支持shared_polymorphic_downcast(或dynamic_pointer_cast或static_pointer_cast为此事)

Update: the shared_ptr in this example is like the one in Boost, but it doesn't support shared_polymorphic_downcast (or dynamic_pointer_cast or static_pointer_cast for that matter)!

我想初始化一个共享指针派生类中不失引用计数:

I'm trying to initialize a shared pointer to a derived class without losing the reference count:

struct Base { };
struct Derived : public Base { };
shared_ptr<Base> base(new Base());
shared_ptr<Derived> derived;

// error: invalid conversion from 'Base* const' to 'Derived*'
derived = base;

到目前为止,一切都很好。没想到C ++库*隐式转换为派生*。不过,我想用code pssed功能前$ P $(即保持引用计数,而向下转换的基指针)。我首先想到的是提供基本转换运算符,使派生可能发生的隐式转换(学究:我会检查下投是有效的,不用担心):

So far, so good. I didn't expect C++ to implicitly convert Base* to Derived*. However, I do want the functionality expressed by the code (that is, maintaining the reference count while downcasting the base pointer). My first thought was to provide a cast operator in Base so that an implicit conversion to Derived could take place (for pedants: I would check that the down cast is valid, don't worry):

struct Base {
  operator Derived* ();
}
// ...
Base::operator Derived* () {
  return down_cast<Derived*>(this);
}

好吧,这并没有帮助。这似乎编译器完全忽略了我的类型转换操作符。任何想法我怎么可能让shared_ptr的分配工作?对于加分:什么样类型的基础* const的是? 常量基​​地* 我理解,但基础* const的?是什么常量是指在这种情况下?

Well, it didn't help. It seems the compiler completely ignored my typecast operator. Any ideas how I could make the shared_ptr assignment work? For extra points: what kind of type Base* const is? const Base* I understand, but Base* const? What does const refer to in this case?

推荐答案

我假设你正在使用的boost :: shared_ptr的 ...我想你想的 dynamic_pointer_cast shared_polymorphic_downcast

I assume you're using boost::shared_ptr... I think you want dynamic_pointer_cast or shared_polymorphic_downcast.

这些都需要多态类型,但是。

These require polymorphic types, however.

什么样类型的基础* const的是? 常量基​​地* 我理解,但基础* const的?是什么常量是指在这种情况下?

what kind of type Base* const is? const Base* I understand, but Base* const? What does const refer to in this case?


  • 常量基​​地* 是一个可变指向一个恒定的基本

  • 基础常量* 是一个可变指向一个恒定的基本

  • 基础* const的是一个常量指针可变基本

  • 基础常量* const的是一个常量指针,以一个恒定的基本

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆