简体   繁体   English

dynamic_cast vs static_cast to void *

[英]dynamic_cast vs static_cast to void*

In the last two lines of below program, static_cast<void*> and dynamic_cast<void *> behave differently. 在下面的程序的最后两行中, static_cast<void*>dynamic_cast<void *>行为有所不同。 From what I understand, The result of a dynamic_cast<void*> always resolves to the address of the complete object. 根据我的理解, dynamic_cast<void*>总是解析为整个对象的地址。 So it uses RTTI in some way. 所以它以某种方式使用RTTI。 Could anyone explain how compilers uses RTTI to differentiate between the two. 任何人都可以解释编译器如何使用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;
}

Possible output: https://ideone.com/WoX5DI 可能的输出: https//ideone.com/WoX5DI

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

From 5.2.7 / 7: 从5.2.7 / 7开始:

If T is "pointer to cv void," then the result is a pointer to the most derived object pointed to by v. Otherwise, a run-time check is applied to see if the object pointed or referred to by v can be converted to the type pointed or referred to by T. 如果T是“指向cv void的指针”,则结果是指向v指向的最派生对象的指针。否则,将应用运行时检查以查看v指向或引用的对象是否可以转换为T指出或引用的类型

So using dynamic_cast<void*>(o) you get a pointer to the first byte of the most "derived" object (if o is polymorphic). 因此,使用dynamic_cast<void*>(o)您将获得指向最“派生”对象的第一个字节的指针(如果o是多态的)。

The code the compiler generates for dynamic_cast<void *>(...) is something like: 编译器为dynamic_cast<void *>(...)生成的代码类似于:

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

This property is often used for serialization. 此属性通常用于序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM