C ++编译器如何优化不正确的层次结构向下转换以导致真正的未定义行为 [英] How can C++ compiler optimize incorrect hierarchical downcast to cause real undefined behavior

查看:77
本文介绍了C ++编译器如何优化不正确的层次结构向下转换以导致真正的未定义行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

class Base {
public:
    int data_;
};

class Derived : public Base {
public:
    void fun() { ::std::cout << "Hi, I'm " << this << ::std::endl; }
};

int main() {
    Base base;
    Derived *derived = static_cast<Derived*>(&base); // Undefined behavior!

    derived->fun(); 

    return 0;
}

根据C ++标准,函数调用显然是未定义的行为。但是,在所有可用的机器和编译器(VC2005 / 2008,RH Linux和SunOS上的gcc)上,它都能按预期工作(打印 Hi!)。有谁知道此代码的配置可能无法正常工作?或者可能是具有相同想法的更复杂示例(请注意,无论如何,派生都不应该携带任何其他数据)?

Function call is obviously undefined behavior according to C++ standard. But on all available machines and compilers (VC2005/2008, gcc on RH Linux and SunOS) it works as expected (prints "Hi!"). Do anyone know configuration this code can work incorrectly on? Or may be, more complicated example with the same idea (note, that Derived shouldn't carry any additional data anyway)?

更新:

从标准5.2.9 / 8:

From standard 5.2.9/8:


指向cv1 B的指针,其中B是类类型,可以将
转换为类型为指向cv2 D的指针的右值,其中D是从B派生(第10条)的
类,如果存在从
指向D的指针到指向B的指针的有效标准转换(4.10),cv2与
cvqualification相同,或大于cvqualification,比cv1相同,并且B不是$ b $ D的虚拟基类。将空指针值(4.10)转换为目标类型的空指针值
如果
类型的右值指向cv1 B的指针指向的B实际上是
的子对象,而B是类型D的对象,则结果指针将指向封闭的
对象

还有一个9.3.1(感谢@)。 Agent_L):

And one more 9.3.1 (thanks @Agent_L):


如果为非X类型的对象
调用了类X的非静态成员函数,或从X派生的类型,则行为是
未定义。

If a nonstatic 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.

谢谢,
Mike。

Thanks, Mike.

推荐答案

函数 fun()实际上并没有做什么事情 this 指针是,并且由于它不是虚函数,因此查找该函数不需要任何特殊操作。基本上,它像任何普通的(非成员)函数一样被调用,但 this 指针有问题。它不会崩溃,这是完全有效的未定义行为(如果不是矛盾的话)。

The function fun() doesn't actually do anything that matters what the this pointer is, and as it isn't a virtual function, there's nothing special needed to look up the function. Basically, it's called like any normal (non-member) function, with a bad this pointer. It just doesn't crash, which is perfectly valid undefined behavior (if that's not a contradiction).

这篇关于C ++编译器如何优化不正确的层次结构向下转换以导致真正的未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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