考虑一下:
#include <iostream>
using namespace std;
class A{
protected:
void some_function(int params)
{
//inside A: do something A related
}
};
class B: public A{
public:
void call_some_function(int params)
{
some_function(params); // Simple call to A::some_function and NOTHING MORE.
}
};
int main(int argc, char *argv[])
{
A* a = new A();
((B*)(a))->call_some_function(20); // Is it OK ?
}
这段代码有效 使用它有什么危险?
最佳答案
在 C 和 C++ 中,通常未定义的行为(将此理解为“非法但编译器允许”)通过指针或对另一种类型对象的引用取消引用一种类型的对象(除了少数异常(exception),例如通过指向基类的指针访问)。这称为严格别名规则。
在这里阅读更多:What is the strict aliasing rule?
您的代码通过指向类型 B 的指针访问类型 A 的对象违反了此规则。
请注意,编译器通常无法验证您的静态转换(在您的情况下,C-cast 等同于 static_cast
)。如果您不确定对象类型,dynamic_cast
可在运行时验证转换是否合法,而 static_cast
仅在编译时检查并允许一些不正确的转换。
关于c++ - 危险类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8432496/