【发布时间】:2016-09-09 22:54:12
【问题描述】:
我注意到奇怪的语义 wrt 绑定对指针和数组的引用,它们分别在指向和数组元素的常量上不同。使用指针可以预见地失败:
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] 的非常量引用绑定到int[5] 类型的对象。为什么允许这样做?
更新: Gotcha #32(第 82 页)在 Stephen C. Dewhurst 的 C++ Gotchas 中描述了类似的问题
【问题讨论】:
-
也可以考虑
int *const &p_ref{p};。 -
@Hurkyl 这只是普通的将 const ref 绑定到非 const 变量吗?
-
大陆 const 位置似乎与此相关:kuhllib.com/2012/01/17/continental-const-placement
标签: c++ arrays pointers c++11 reference