gpt4 book ai didi

c++ - 重新解释 Actor 转换

转载 作者:行者123 更新时间:2023-12-02 18:10:16 25 4
gpt4 key购买 nike

据我对有关[expr.reinterpret.cast]的标准的理解—但如果我错了,请纠正我 — 将指向成员函数的指针转换为其他指向成员函数的指针并返回到其原始值实际上是合法的、定义良好的行为。如7.6.1.10部分所述:

A prvalue of type “pointer to member of X of type T1” can beexplicitly converted to a prvalue of a different type “pointer tomember of Y of type T2” if T1 and T2 are both function types or bothobject types.59 The null member pointer value ([conv.mem]) isconverted to the null member pointer value of the destination type.The result of this conversion is unspecified, except in the followingcases:

(10.1) Converting a prvalue of type “pointer to member function” to adifferent pointer-to-member-function type and back to its originaltype yields the original pointer-to-member value.

(10.2) Converting a prvalue of type “pointer to data member of X oftype T1” to the type “pointer to data member of Y of type T2” (wherethe alignment requirements of T2 are no stricter than those of T1) andback to its original type yields the original pointer-to-member value.

这似乎与常规函数指针相反,在常规函数指针中进行相同的转换会导致未指定的行为。如7.6.1.6部分所述:

A function pointer can be explicitly converted to a function pointerof a different type. [Note 4: The effect of calling a function througha pointer to a function type ([dcl.fct]) that is not the same as thetype used in the definition of the function is undefined([expr.call]). — end note] Except that converting a prvalue of type“pointer to T1” to the type “pointer to T2” (where T1 and T2 arefunction types) and back to its original type yields the originalpointer value, the result of such a pointer conversion is unspecified.[Note 5: See also [conv.ptr] for more details of pointer conversions.— end note]

一些示例代码来说明两种类型转换之间的区别:

struct s { auto f() -> void {} };
struct t { auto g(t) -> t { return {}; } };

auto f() -> void {};
auto g(t) -> t { return {}; }

auto main() -> int {
auto ps = &s::f;
auto pt = reinterpret_cast<decltype(&t::g)>(ps);
(s{}.*reinterpret_cast<decltype(&s::f)>(pt))(); // well-defined behavior

auto pf = &f;
auto pg = reinterpret_cast<decltype(&g)>(pf);
reinterpret_cast<decltype(&f)>(pg)(); // unspecified behavior
}

常规函数指针转换导致未指定行为的原因是什么?为什么这两种类型的转换不是明确定义的就是未指定的?允许明确定义常规函数指针转换会产生什么后果?当两种类型的转换看起来具有如此相似的性质时,这种区别让我觉得很奇怪。

最佳答案

你只是误读了第二句话。在突出显示的句子中,主子句之前的从属子句中的所有内容“此类指针转换的结果未指定”都说明了该主语句的异常。

reinterpret_cast往返转换保证对函数指针的作用与对成员函数指针的作用完全相同(但不适用于对象指针或数据成员指针,因为它受到对齐的限制)。

因此,您给出的两个示例都会在 reinterpret_cast 之后产生指定的函数/成员指针值。并且该程序具有明确定义的行为。

第二个引用只是使用了更紧凑的措辞来表示除了使用转换结果之外,没有指定任何关于 reinterpret_cast<decltype(&g)>(pf) 的内容。 .

reinterpret_cast<decltype(&t::g)>(ps) 也是如此。 。相关声明位于突出显示部分之前的第一个引用中:“此转换的结果未指定,但以下情况除外:

关于c++ - 重新解释 Actor 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72504041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com