gpt4 book ai didi

c++ - 忽略 cv 限定符的 typeid 运算符背后的基本原理是什么

转载 作者:搜寻专家 更新时间:2023-10-31 01:30:01 25 4
gpt4 key购买 nike

来自 C++ 语言标准,来自 ISO/IEC 14882:2003 的 §5.2.8,引用,

The top-level cv-qualifiers of the lvalue expression or the type-id that is the operand of typeid are always ignored.

这个决定的理由是什么。它在类型系统中打了一个洞,是违反直觉的。 const 信息(或 volatile 部分)在编译时已知,因此如果 typeid 仅考虑 cv 限定符,则不会有开销。

最佳答案

尽管能够使用 constvolatileconst volatile 变体重载非静态成员函数(参见 [class.mfct.nonstatic] ), D, const D, volatile D, and const volatile D (对于一些非cv-限定类型 D) 并非无关;该标准在 [basic.type.qualifier] 中指定,对于每个 cv-unqualified type,都有一个不同的 const-qualified,volatile-具有相同表示和对齐要求的类型的限定和 const volatile 限定“版本”。如果 Dconst D 可能彼此无关(例如,通过具有不同的表示、存储要求,或者在类的情况下,不同的成员),那么很多语言就会崩溃。

例如,D& 类型的对象可隐式转换为const D&volatile D&const volatile D&(参见 [conv.qual])。但是,如果允许 Dconst D 无关,那么这种转换就没有意义。

还要考虑标准中的许多地方指定忽略顶级 cv 限定符:

  • [over.load] 指定:

    Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.

  • [temp.param] 指定:

    The top-level cv-qualifiers on the template-parameter are ignored when determining its type.

  • [basic.life],在指定如何重用生命周期结束的对象的存储时,提到:

    the new object is of the same type as the original object (ignoring the top-level cv-qualifiers)

  • [over.best.ics] 指定:

    Any difference in top-level cv-qualification is subsumed by the initialization itself and does not constitute a conversion. [Example: a parameter of type A can be initialized from an argument of type const A. The implicit conversion sequence for that case is the identity sequence; it contains no “conversion” from const A to A. ]

  • [temp.deduct.call] 指定:

    If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.

    和:

    If P is a cv-qualified type, the top level cv-qualifiers of P’s type are ignored for type deduction.

    ([temp.deduct.conv] 有类似的语言。)

  • [except.throw] 指定:

    A throw-expression initializes a temporary object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from “array of T” or “function returning T” to “pointer to T” or “pointer to function returning T”, respectively.

  • [except.handle] 指定:

    A handler is a match for a throw-expression with an object of type E if

    — The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or …

如果 Dconst Dvolatile Dconst volatile D,则所有这些都必须更改code> 可以是不相关的类型。

关于c++ - 忽略 cv 限定符的 typeid 运算符背后的基本原理是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717494/

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