gpt4 book ai didi

c++ - 检查 ptr 是否属于虚拟类?

转载 作者:太空狗 更新时间:2023-10-29 21:07:17 26 4
gpt4 key购买 nike

我的代码表现不稳定,我能够用下面的代码迷你重现它。 ( codepad link )

来自 http://www.cppreference.com/wiki/keywords/dynamic_cast

If you attempt to cast to a pointer type, and that type is not an actual type of the argument object, then the result of the cast will be NULL.

根据我的理解,this_test 应该为空。它不是。我如何检查该虚拟指针是否实际上是虚拟对象的指针?

#include <ios>
struct Dummy{ virtual void dummyfn(){} };

int main(){
Dummy* this_test = dynamic_cast<Dummy*>((Dummy*)0x123);
//assert(this_test==0);
cout << std::hex << this_test<<endl;
return 0;
}

输出:

0x123

最佳答案

一厢情愿...:)

我相信 dynamic_cast 只适用于多态情况下的向下转换,而不是任何任何类型的转换。它不像编译器存储每个变量的类型信息,所以它不能做你想的事——我很确定这是未定义的行为。

关于c++ - 检查 ptr 是否属于虚拟类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5503714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com