以类型安全的方式将指针转换为指针 [英] Casting pointer to pointer in a type-safe manner

查看:108
本文介绍了以类型安全的方式将指针转换为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

class Base
{
public:
   virtual ~Base() = default;
};

class Derived : public Base { };

int main(void)
{
  Derived d;
  Base* pb = &d;
  Base** ppb = &pb;

  Derived** ppd = ...; // Can this be defined in a type-safe manner?

  return 0;
}

是否可以为分配给ppd的类型提供安全的表达式,而无需引入类型为Derived*的中间变量?

Is it possible to give a type-safe expression for the assignment to ppd, without introducing an intermediary variable of type Derived*?

推荐答案

AFAIK,并非没有声明指向dDerived指针.指向d(pb)的Base指针已经通过抽象丢失了类型信息,没有不安全的强制转换就无法恢复.

AFAIK, not without declaring a Derived pointer to d. The Base pointer to d (pb) has already lost type information through abstraction, which cannot be recovered without a unsafe cast.

由于要声明指向Derived的指针,因此首先需要一个指向Derived的指针.例如:

Since you're declaring a pointer to a pointer to a Derived, you need a pointer to a Derived first. Eg:

Derived* pd = &d;
Derived** ppd = &pd;

这两个定义都是类型安全的,在编译时检查.

Both of those definitions are type-safe, checked at compile time.

这篇关于以类型安全的方式将指针转换为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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