加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将const T(&ref)[N]绑定到类型为T [N]的对象

发布时间:2020-12-16 10:02:43 所属栏目:百科 来源:网络整理
导读:我注意到奇怪的语义wrt绑定对指针和数组的引用,这些指针和数组分别在指向和数组元素的常量上有所不同.使用指针,这可以预测失败: int* p{};const int* p_ref{p}; non-const lvalue reference to type 'const int *' cannot bind to a value of unrelated typ
我注意到奇怪的语义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 *'

有道理,指向int和指针指向const-int是两种不同的类型,在& amp;之前添加一个const.允许编译器生成一个临时的,有效的,但不会改变上面的内容.

但是,我认为应该与数组类似的不是

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

clang和gcc都在没有抱怨的情况下编译上面的内容,但为什么呢?我将const int [5]的非const引用绑定到int [5]类型的对象.为什么允许这样做?

更新:Stephen C. Dewhurst在C++ Gotchas年由Gotcha#32(第82页)描述了类似的问题

解决方法

使用您的第一个示例,如果允许,则可能会破坏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

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

指针指针有类似的问题.通常情况下,我们将非const 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读