有没有实际用途动态转换void指针? [英] Are there practical uses for dynamic-casting to void pointer?

查看:113
本文介绍了有没有实际用途动态转换void指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中, T q = dynamic_cast (p); 构造执行指针 p 到一些其他指针类型 T 必须出现在动态类型 * p 的继承层次结构中顺序成功。



但是,也可以执行 dynamic_cast< void *>(p),它将简单地返回一个指向最大派生对象的指针(见C ++ 11中的5.2.7 :: 7)。我理解这个特性可能是在执行动态转换时自由出来的,但它在实践中有用吗?毕竟,它的返回类型最多是 void * ,所以这有什么好处?

解决方案

dynamic_cast< void *>()确实可以用来检查身份,即使处理多重继承。



尝试此代码:

  #include< iostream> 

class B {
public:
virtual〜B(){}
};

class D1:public B {
};

class D2:public B {
};

class DD:public D1,public D2 {
};

命名空间{
bool eq(B * b1,B * b2){
return b1 == b2;
}

bool eqdc(B * b1,B * b2){
return dynamic_cast< void *>(b1)== dynamic_cast< void *> ;
}
};

int
main(){
DD * dd = new DD();
D1 * d1 = dynamic_cast< D1 *(dd);
D2 * d2 = dynamic_cast< D2 *>(dd)​​;

std :: cout<< eq:<< eq(d1,d2)< ,eqdc:< eqdc(d1,d2) \\\
;
return 0;
}

输出:

  eq:0,eqdc:1 


In C++, the T q = dynamic_cast<T>(p); construction performs a runtime cast of a pointer p to some other pointer type T that must appear in the inheritance hierarchy of the dynamic type of *p in order to succeed. That is all fine and well.

However, it is also possible to perform dynamic_cast<void*>(p), which will simply return a pointer to the "most derived object" (see 5.2.7::7 in C++11). I understand that this feature probably comes out for free in the implementation of the dynamic cast, but is it useful in practice? After all, its return type is at best void*, so what good is this?

解决方案

The dynamic_cast<void*>() can indeed be used to check for identity, even if dealing with multiple inheritance.

Try this code:

#include <iostream>

class B {
public:
    virtual ~B() {}
};

class D1 : public B {
};

class D2 : public B {
};

class DD : public D1, public D2 {
};

namespace {
    bool eq(B* b1, B* b2) {
        return b1 == b2;
    }

    bool eqdc(B* b1, B *b2) {
        return dynamic_cast<void*>(b1) == dynamic_cast<void*>(b2);
    }
};

int
main() {
    DD *dd = new DD();
    D1 *d1 = dynamic_cast<D1*>(dd);
    D2 *d2 = dynamic_cast<D2*>(dd);

    std::cout << "eq: " << eq(d1, d2) << ", eqdc: " << eqdc(d1, d2) << "\n";
    return 0;
}

Output:

eq: 0, eqdc: 1

这篇关于有没有实际用途动态转换void指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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