指针的指针的reinterpret_cast

时间:2019-05-01 02:18:02

标签: c++ reinterpret-cast

如果我有一个指向指针Derived**的派生类指针,并希望将其转换为指向指针Base**的基类指针,则使用static_cast<Base**>(ppd)不会编译,因此我被迫使用reinterpret_cast<Base**>,似乎效果很好。是否有一个原因?在进行这种reinterpret_cast时,我有什么需要注意的注意事项吗?

下面是我写的一段示例代码:

struct Base {
    Base(int x0) : x(x0) {}
    int x;
};

struct Derived : Base {
    Derived(int x0, int y0): Base(x0), y(y0) {}
    int y;
};

void foo(Base** ppb) {
    *ppb = new Derived(5, 7);
}

void bar(Derived** ppd) {
    foo(reinterpret_cast<Base**>(ppd));
}

int main() {
    Base* pb = new Base(3);
    cout << pb->x << endl;
    delete pb;

    foo(&pb);
    cout << pb->x << ' ' << static_cast<Derived*>(pb)->y << endl;
    delete pb;

    Derived* pd = new Derived(2,4);
    cout << pd->x << ' ' << pd->y << endl;
    delete pd;

    bar(&pd);
    cout << pd->x << ' ' << pd->y << endl;
    delete pd;
}

2 个答案:

答案 0 :(得分:1)

reinterpret_cast<Base**>(ppDerived)定义明确。如果对js的指针指向派生的指针,则取消对结果的引用是未定义的行为,而不是您可以执行的操作。 UB可能的症状之一是“看起来工作正常”。

您可能想要的是:

Base* foo() {
  return new Derived(5, 7);
}

Derived* bar() {
  return static_cast<Derived*>(foo());
}

不包含UB,并且在逻辑上是等效的。

或者您可以这样做:

template<class...Ts>
using sink=std::function<void(Ts...)>;

void foo(sink<Base*> ppb) {
  ppb(new Derived(5, 7));
}

void bar(sink<Derived*> ppd) {
  foo([&](Base*b){ ppd(static_cast<Derived*>(b)); });
}

甚至

void foo(Base** ppb) {
  *ppb = new Derived(5, 7);
}

void bar(Derived** ppd) {
  Base*p=0;
  foo(&p);
  *ppd=static_cast<Derived*>(p);
}

答案 1 :(得分:1)

您实际上根本不需要reinterpret_cast

void bar(Derived** ppd) {
    Base *base;
    foo(&base);
    *ppd = static_cast<Derived*>(base);
}
相关问题