在C++中,"dynamic_cast"缓慢是一个众所周知的事实.我想到了以下简单的方法来了解层次结构中对象的类型.有人可以解释一下这是否比dynamic_cast慢?如果不是,那么为什么不是普遍的做法,因为速度的C++对C最差的缺点?
struct Base {
unsigned m_type;
Base(unsigned type): m_type(type) {}
Base(): m_type(0) {}
};
struct Derived1: Base {
Derived1(): Base(1) {}
Derived1(int type): Base(type) {}
};
struct Derived2: Base {
Derived2(): Base(2) {}
};
struct Derived3: Derived1 {
Derived3(): Derived1(3) {}
};
void my_func(Base * p) {
if (p - > m_type == 0) {}
else if (p - > m_type == 1) {}
else if (p - > m_type == 2) {}
else if (p - > m_type == …Run Code Online (Sandbox Code Playgroud) 在查看从旧版本的Visual Studio(6)移植到新版本(2017)的继承项目时,我们偶然发现了这个运行时错误,因为我们在使用dynamic_cast<>()基类后得到了意外的NULL .这是一个代表性的样本:
鉴于此代码:
class a { public: a() {}; virtual ~a() {}; };
class b :public a { public: b() {}; virtual ~b() {}; };
class c : public b { public: c() {}; virtual ~c() {}; };
int main()
{
a *a_ = new b();
b *b_ = new c();
c *c_1 = dynamic_cast<c*>(b_); //<-- returns c_1 = non-null(actual pointer value)
c *c_2 = dynamic_cast<c*>(a_); //<-- returns c_2 = NULL
}
Run Code Online (Sandbox Code Playgroud)
我相信作者已经正确设置了所有课程dynamic_cast<>().类c'是'a类似乎看起来很满意,而类c'是'类b'所以看起来很满意.
我想知道问题是否存在于a_ …
假设代码是这样的:
#include <iostream>
using namespace std;
class dog
{
public:
virtual ~dog()
{
}
};
class yellowdog : public dog
{
int age;
public:
void bark() { cout << "woof." << endl;}
};
int main()
{
dog *pd = new dog();
yellowdog *py = dynamic_cast<yellowdog*>(pd);
py->bark();
cout << "py = " << py << endl;
cout << "pd = " << pd << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
woof.
py = 0x0
pd = 0x7fd4d34000e0
Run Code Online (Sandbox Code Playgroud)
我明白了为什么PY = 0.我知道,有一个运行时检查,并在运行时检查,有一项不合格转换dog到yellowdog,PY …
我有一个结构
struct foo : public std::map<std::string, int>
{
};
Run Code Online (Sandbox Code Playgroud)
和儿童结构;
struct bar : public foo
{
int another_member;
}
Run Code Online (Sandbox Code Playgroud)
但我不能使用bar* b = dynamic_cast<bar*>(f)f是指向foo的指针.
即使我重构foo到
struct foo
{
std::map<std::string, int> m;
};
Run Code Online (Sandbox Code Playgroud)
我还有问题.我玩过我的RTTI设置无济于事.到底是怎么回事?
错误是:
错误C2683:'dynamic_cast':'Credit :: WaterfallSimulationResult'不是多态类型