c++ - 该代码标准是否合规?

标签 c++ c++11 language-lawyer c++14 c++98

所以代码是

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 派生的类型。

关于c++ - 该代码标准是否合规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990849/

相关文章:

c++ - 如何强制编译器为手动切换生成等效代码?

c++ - std::lists 的 std::vector 中的不可复制元素

c - 我们不能用指针进行什么操作?

不包含原型(prototype)的函数类型的兼容性

c++ - decltype(foo(1)) 应该实例化 constexpr 函数模板 foo 吗?

C#6/C++ ref 关键字错误

c++ - 隐藏 typedef 实现

c++ - 在其他类中使用类类型时遇到问题

c++ - 如果内部的总工作相同,将 for 循环拆分为多个 for 循环的开销是多少?

c++ - 制作 shared_ptr 的拷贝时会发生什么?