将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗?

编程入门 行业动态 更新时间:2024-10-27 12:32:11
本文介绍了将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

将指向派生类成员变量的指针强制转换为指向基类成员变量的指针合法吗?

本文发布于:2023-07-28 02:46:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   变量   成员   转换为   派生类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!