gpt4 book ai didi

c++ - T* 和常量 T*

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:23 25 4
gpt4 key购买 nike

我相信这可能适用于许多 T,但我确信这适用于整数。作为学习 C++ 的一部分,我试图用标准中的语言来解释以下行为。

typedef const int * constintptr;
typedef int * intptr;

intptr p;
constintptr cp = p;
const constintptr& crcp = p;
//constintptr & rcp = p;

查看 n3337,第 8.5.3 节。似乎可以通过说 int* 可转换为 const int * prvalue,但引用不兼容来解释此行为。 (如果我错了,请纠正我)。

我看到这是可取的行为(或者我们可以颠覆 const),并且这种行为的可取性不是这个问题的目的。

问题是在标准中指定(或暗示)它们 intptr 和 constintptr 不引用兼容。

最佳答案

相同的部分,8.5.3/4(从 n3797 开始编号,我有)定义了引用兼容:

Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is reference-related to “cv2 T2” if T1 is the same type as T2 , or T1 is a base class of T2 . “cv1 T1” is reference-compatible with “cv2 T2” if T1 is reference-related to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2

所以你的类型 T1 是 int* 和 T2 int const*。它们不是同一类型。它们中的任何一个都不是另一个的基类(因为它们根本就不是一个类)。因此,它们与引用无关。

当标准说“cv1 T1”时,它表示将 0 个或多个 constvolatile 应用于 T1 类型的结果的任何类型。它表示文本替换,也就是说它不表示由0个或多个关键字constvolatile声明的任何类型> 后跟另一个标记序列,它是 T1 的类型声明。

因此您可能误解了这一点,以至于您认为 const int*int* 的 cv 限定版本。如果是,那么根据一般规则,它们将与引用相关,因此标准中需要有文本来做出异常(exception)。但事实并非如此。 int *constint* 的 cv 限定版本。

关于c++ - T* 和常量 T*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915139/

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