int val2 = 38;
int *ptr = &val2;
const int *&ptrRef = ptr; // ERROR
int i = 92;
int &ref_i = i;
const int &ref_i2 = ref_i; // OK
为什么我不能有一个引用非 const 指针的 const 引用?我想如果你访问 const ptrRef
标识符,它将处理 val2
作为常量。当您访问 ptr
,它将处理 val2
作为非常量。这适用于代码的底部,所以我不明白为什么它不适用于指针。
最佳答案
East-const使它更清楚:
int const * & ptrRef = ptr; // ERROR
它是常量的指针。但是,ptr
是不同的类型。您不能将引用绑定(bind)到不同的类型。它需要转换,使初始化器成为临时的( ptr
转换为 int const*
)。Now, there's a more confusing catch: const references can bind to temporaries, extending their lifetime: Why do const references extend the lifetime of rvalues?
They e.g. allow funtions to take arguments by
const&
and still be callable with temporaries:void foo(std::string const&); foo("foor"s+"bar"s); // still ok
关于c++ - 将 const 指针引用绑定(bind)到非 const 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62800680/