将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗? [英] Is it legal to cast a pointer-to-derived-class-member-variable to a pointer-to-base-class-member-variable?

查看:48
本文介绍了将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要用于访问成员指针的指针的类型正确,以下内容是否会导致不确定的行为?

Does the following lead to undefined behavior as long as the pointer being used to access the pointer-to-member is of a correct type?

如果是的话,为什么我需要演员阵容?没有它,看起来会好很多(是的,我知道这只是一个意见问题).

And if so, why do I need the cast? It would look a lot nicer without it (and yes, I know that's just a matter of opinion).

struct base {
    int foo(int base::* ptr) {
        return this->*ptr;
    }
};

struct sub : base {
    int blah{ 42 };
};

int main() {
    return sub{}.foo(static_cast<int base::*>(&sub::blah));
}

推荐答案

只要用于访问成员指针的指针的类型正确,以下内容是否会导致不确定的行为?

Does the following lead to undefined behavior as long as the pointer being used to access the pointer-to-member is of a correct type?

不,它的格式正确.规则来自 [expr.mptr.oper] 是:

No, it's well formed. The rule, from [expr.mptr.oper] is:

如果E1的动态类型不包含E2所引用的成员,则该行为是不确定的.

If the dynamic type of E1 does not contain the member to which E2 refers, the behavior is undefined.

* this 动态类型>是 sub ,它确实包含该成员,所以很好.

The dynamic type of *this is sub, which does contain the member, so this is fine.

如果是的话,为什么我需要演员阵容?

And if so, why do I need the cast?

因为这是本质上不安全的转换,并且经验法则是,本质上不安全的操作应大声且可见.在这种情况下,可以,但是那只是因为您要小心.需要施展力量,您必须考虑一下.

Because it's an inherently unsafe cast, and the rule of thumb is that inherently unsafe operations should be loud and visible. In this specific case, it's fine, but that's only because you were being careful. Requiring the cast forces you to have to think about it.

一个更简单的示例可能是只查看指针而不是成员指针.在简单的层次结构中(假定是公共的,无歧义的等),将 Derived * 强制转换为 Base * 始终是安全的.那里没有任何问题,因此您无需编写演员表.但是,将 Base * 强制转换为 Derived * 并不总是安全的……您可能在此处没有 Derived * .但是,这永远都不安全-禁止完全强制转换会很糟糕.因此,安全类型转换是隐式的,但不安全类型转换必须是显式的.

A simpler example might be to look at just the pointers instead of the pointer-to-member. In a simple hierarchy (assuming public, non-ambiguous, etc.), it is always safe to cast a Derived* to a Base*. There's nothing problematic there, so you don't need to write a cast. However, it is not always safe to cast a Base* to a Derived*... you might not have a Derived* there. But, it's not never safe - disallowing that cast entirely would be bad. So the safe cast is implicit, but the unsafe cast must be explicit.

这篇关于将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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