簡體   English   中英

dynamic_cast vs static_cast to void *

[英]dynamic_cast vs static_cast to void*

在下面的程序的最后兩行中, static_cast<void*>dynamic_cast<void *>行為有所不同。 根據我的理解, dynamic_cast<void*>總是解析為整個對象的地址。 所以它以某種方式使用RTTI。 任何人都可以解釋編譯器如何使用RTTI來區分這兩者。

#include <iostream>
using namespace std;
class Top {
protected:
int x;
public:
    Top(int n) { x = n; }
    virtual ~Top() {} 
    friend ostream& operator<<(ostream& os, const Top& t) {
        return os << t.x;
    }
};
class Left : virtual public Top {
protected:
    int y;
public:
    Left(int m, int n) : Top(m) { y = n; }
};
class Right : virtual public Top {
protected:
    int z;
public:
    Right(int m, int n) : Top(m) { z = n; }
};
class Bottom : public Left, public Right {
    int w; 
public:
    Bottom(int i, int j, int k, int m): Top(i), Left(0, j), Right(0, k) { w = m; }
    friend ostream& operator<<(ostream& os, const Bottom& b) {
        return os << b.x << ',' << b.y << ',' << b.z<< ',' << b.w;
    }
};
int main() {
    Bottom b(1, 2, 3, 4);
    cout << sizeof b << endl;
    cout << b << endl;
    cout << static_cast<void*>(&b) << endl;
    Top* p = static_cast<Top*>(&b);
    cout << *p << endl;
    cout << p << endl;
    cout << static_cast<void*>(p) << endl;
    cout << dynamic_cast<void*>(p) << endl;
    return 0;
}

可能的輸出: https//ideone.com/WoX5DI

28
1,2,3,4
0xbfcce604
1
0xbfcce618
0xbfcce618
0xbfcce604

從5.2.7 / 7開始:

如果T是“指向cv void的指針”,則結果是指向v指向的最派生對象的指針。否則,將應用運行時檢查以查看v指向或引用的對象是否可以轉換為T指出或引用的類型

因此,使用dynamic_cast<void*>(o)您將獲得指向最“派生”對象的第一個字節的指針(如果o是多態的)。

編譯器為dynamic_cast<void *>(...)生成的代碼類似於:

static_cast<void*>(dynamic_cast<most_derived_type *>(...))

此屬性通常用於序列化。

暫無
暫無

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

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