编译器添加的优化引起“最终”的不同行为。方法 [英] Compiler added optimization causes different behavior for "final" methods

查看:185
本文介绍了编译器添加的优化引起“最终”的不同行为。方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct B { 
  virtual void foo ()
  { cout << "B::foo()\n"; }
};

struct D : B { 
  void foo () //final
  { cout << "D::foo()\n"; }
};

int main ()
{
  B *pB = new B;
  D *pD = static_cast<D*>(pB);
  pB->foo();
  pD->foo();
}

输出预期行为:

B::foo()
B::foo()

如果我们使 D :: foo() final,那么输出是令人愉快的:

If we make the D::foo() final, then the output is pleasantly different:

B::foo()
D::foo()

$ b b

这意味着 virtual 功能不会在使用指针/引用调用该方法时被踢入,该类的方法声明为 final

也就是说, final 不仅仅是一个编译时检查,也有助于运行时行为。

Which means that virtual functionality is not kicked-in when the method is invoked with pointer/reference of a class which has that method declared as final.
Also it means that, final isn't just a compile-time check but also contributes to runtime behavior.

这是所有编译器的标准行为。我已经用g ++ 4.7测试。

Is it a standard behavior for all compilers. I have tested with g++4.7.

编辑

生成一个新问题。关闭此问题。

推荐答案

D *pD = static_cast<D*>(pB);

使用此语句,您放弃了获得健全程序行为的权利。如果给出 static_cast 实际上不是类型 D c>或 D 的派生类之一(它不是)。

With this statement, you gave up the right to having sane program behavior. C++ does not require this operation to work if what static_cast is given is not actually of type D or one of D's derived classes (which it isn't).

有一个原因为什么 dynamic_cast 存在;一个适当的 dynamic_cast 会很快失败,返回 nullptr 非法投射。

There's a reason why dynamic_cast exists; a proper dynamic_cast would have quickly failed on this, returning nullptr for an illegal cast.

这篇关于编译器添加的优化引起“最终”的不同行为。方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆