加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C编译器如何优化错误的分层向下转换以导致真正的未定义行为

发布时间:2020-12-16 10:46:21 所属栏目:百科 来源:网络整理
导读:请考虑以下示例: 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_castDerived*(base); // Undefined behavior! deri
请考虑以下示例:

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)上,它按预期工作(打印“嗨!”).有谁知道配置此代码可以正常工作?或者可能是具有相同想法的更复杂的例子(注意,Derived不应该携带任何额外的数据)?

更新:

从标准5.2.9 / 8:

An rvalue of type “pointer to cv1 B”,where B is a class type,can be
converted to an rvalue of type “pointer to cv2 D”,where D is a
class derived (clause 10) from B,if a valid standard conversion from
“pointer to D” to “pointer to B” exists (4.10),cv2 is the same
cvqualification as,or greater cvqualification than,cv1,and B is not
a virtual base class of D. The null pointer value (4.10) is converted
to the null pointer value of the destination type. If the rvalue of
type “pointer to cv1 B” points to a B that is actually a subobject of
an object of type D,the resulting pointer points to the enclosing
object of type D. Otherwise,the result of the cast is undefined.

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

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.

谢谢,
麦克风.

解决方法

fun()函数实际上并没有做任何与this指针有关的事情,因为它不是虚函数,所以查找函数没有什么特别之处.基本上,它被称为任何普通(非成员)函数,这个指针不好.它只是不崩溃,这是完全有效的未定义行为(如果这不是一个矛盾).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读