该代码标准是否合规?
Is this code standard compliant or not?
所以代码是
class A
{
public:
int i;
A(){
i = 5;
}
};
class B : public A
{
public:
void someFunc();
};
class C
{
A myObj;
public:
void func(){
B* foo = reinterpret_cast<B*>(&myObj);
foo->someFunc();
}
};
假设 类 将保持原样并且永远不会改变,那么 reinterpret_cast 的这种用法是否正确(我认为不是)?如果不是,那么这里违反了 C++ 标准的哪些具体部分(您可以使用任何版本)?
你的程序确实诱发了UB。 §9.3.1/2:
If a non-static member function of a class X
is called for an object
that is not of type X
, or of a type derived from X
, the behavior is
undefined.
A
不是 B
类型或派生自 B
.
的类型
所以代码是
class A
{
public:
int i;
A(){
i = 5;
}
};
class B : public A
{
public:
void someFunc();
};
class C
{
A myObj;
public:
void func(){
B* foo = reinterpret_cast<B*>(&myObj);
foo->someFunc();
}
};
假设 类 将保持原样并且永远不会改变,那么 reinterpret_cast 的这种用法是否正确(我认为不是)?如果不是,那么这里违反了 C++ 标准的哪些具体部分(您可以使用任何版本)?
你的程序确实诱发了UB。 §9.3.1/2:
If a non-static member function of a class
X
is called for an object that is not of typeX
, or of a type derived fromX
, the behavior is undefined.
A
不是 B
类型或派生自 B
.