对指针的常量引用

问题描述 投票:0回答:1

当我有一个指针的 const 引用时,我为什么能够更改指针指向的对象的值,const 在这个例子中意味着, 存储在指针中的地址无法更改,因为引用是常量。 但我们可以通过引用改变指针指向的对象的值

#include <iostream>

int main(){
    int n = 5;
    int *ptr = &n;
    const auto &refOfPtr = ptr; 
    *refOfPtr = 10;
    std::cout << n << std::endl;
    
}
c++ pointers reference constants
1个回答
0
投票

您有一个对指针的常量引用,因此您无法更改它指向的位置。 IE。

refOfPtr
的类型是
int *const&
,对指向(可变)整数的 const 指针的引用。

但是它指向一个可变对象,所以你可以通过这个指针改变该对象的内容。

© www.soinside.com 2019 - 2024. All rights reserved.