gpt4 book ai didi

c++ - 将 const T (&ref)[N] 绑定(bind)到 T[N] 类型的对象

转载 作者:太空狗 更新时间:2023-10-29 20:10:46 26 4
gpt4 key购买 nike

我注意到奇怪的语义 wrt 对指针和数组的绑定(bind)引用分别在指向和数组元素的常量性方面有所不同。使用指针这会失败:

int* p{};
const int*& p_ref{p};

non-const lvalue reference to type 'const int *' cannot bind to a  value of unrelated type 'int *'

有道理,pointer-to-int 和 pointer-to-const-int 是两种不同的类型,在 & 前加一个 const 可以让编译器产生一个临时的,有效,但不会改变上述内容。

然而,我认为应该类比数组的不是

int arr[5]{};
const int (&arr_ref)[5]{arr};

clang 和 gcc 都毫无怨言地编译了上面的代码,但是为什么呢?我将对 const int[5] 的非常量引用绑定(bind)到 int[5] 类型的对象。为什么允许这样做?

更新:C++ Gotchas 中的 Gotcha #32(第 82 页)描述了一个类似的问题。 Stephen C. Dewhurst 着

最佳答案

对于您的第一个示例,如果允许这样做,就有可能破坏 const 的正确性。

int *p{};
const int*& p_ref{p}; // pretend this is okay
const int x = 10;
p_ref = &x; // storing the address of a const int in a const int*, okay
*p = 5; // Should be okay, because p is int*, not const int*,
// but oops, just modified a const value

对数组的引用没有这个问题,因为你不能将数组指向其他地方(因为它不是指针)。

指向指针的指针也存在类似的问题。通常情况下,我们将非常量 T 的地址存储在 const T* 中。因为这没问题,所以人们倾向于认为应该可以将 T* 的地址存储在 const T** 中。但这会导致与上面的引用示例相同的问题:

int* p;
const int** pp = &p; // forbidden, but pretend it's okay for now
const int x = 10;
*pp = &x; // storing the address of a const int in a const int*, okay
*p = 5; // oops, modified a const int

关于c++ - 将 const T (&ref)[N] 绑定(bind)到 T[N] 类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37215146/

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