向下转换基本类型 [英] Downcasting a base type

查看:230
本文介绍了向下转换基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,如果Base类对象被实例化为基础对象,它是未定义的行为,然后被向下转换为派生对象?

In C++, is it Undefined Behavior if a Base class object is instantiated as a base object, and subsequently downcast to a derived object?

当然,我认为它必须是未定义的行为,因为Derived类对象可能有成员变量, t。因此,如果类被实例化为一个基础对象,这意味着通过Derived类指针访问它们将会导致未定义的行为。这些变量实际上不会存在。

Of course, I would assume it definitely must be undefined behavior, because the Derived class object might have member variables which the base class doesn't. So these variables wouldn't actually exist if the class was instantiated as a base object, which means that accessing them through a Derived class pointer would have to cause Undefined Behavior.

但是,如果Derived类只提供额外的成员函数,但不包括任何进一步的成员数据呢?例如:

But, what if the Derived class simply provides extra member functions, but doesn't include any further member data? For example:

class Base
{
    public:
    int x;
};

class Derived : public Base
{
    public:
    void foo();    
};

int main()
{
    Base b;
    Derived* d = static_cast<Derived*>(&b);
    d->foo(); // <--- Is this undefined behavior?
}

此程序是否导致未定义的行为?

Does this program cause undefined behavior?

推荐答案

是的,它还是未定义的行为,因为你向编译器说明了 d

Yes, it's still undefined behavior, because you're lying to the compiler about the real type of d.

请参阅标准5.2.9 / 8:

See the standard 5.2.9/8:


类型为指向cv1 B的指针的值,
其中B是类类型,可以是
转换为类型$ b的值
指向cv2的指针D ,其中D是来自B的类
,如果存在从指针到
D到到B的指针的有效的
标准转换(4.10),则
cv2是与cb相同的cvqualification,或
比cv1和cb更大的cvqualification
B不是D的虚拟基类。
空指针值(4.10)是
转换为空指针值
的目标类型。如果
的右值类型指向cv1 B的指针指向一个B
,它实际上是一个类型为D的
对象的子对象,结果
指针指向包含对象
类型为D.否则,
的转换结果未定义。

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.

如果指针指向的 B 实际上不是 D 派生类的一部分,则转换未定义行为。

The final two sentences say that if the B pointed to by the pointer is not actually part of a D derived class, the cast is undefined behavior.

这篇关于向下转换基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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