簡體   English   中英

指針的reinterpret_cast指針

[英]reinterpret_cast of pointer to pointer

如果我有一個指向Derived**指針的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;
}

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);
}

您實際上根本不需要reinterpret_cast

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM