c++ - 将 const 指针引用绑定(bind)到非 const 指针

标签 c++ pointers reference

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/

相关文章:

c - 指针指向的值没有更新

perl - 我如何在 Perl 中定义匿名标量引用?

c++ - 强制资源从非 mfc 应用程序中的 dll 加载的 WTL 方式? (我们使用的是 WTL/ATL,而不是直接的 win32)

c++ - 链接到库需要 MFC80U.LIB

c++ - 将 C++ 类私有(private)变量转换为公共(public)变量

c++ - Rust 中指针和引用的区别

c++ - 通过引用将派生类指针传递给期望基指针的函数

c++ - glGetUniformLocation 为第一个以外的采样器返回 -1?

c++ - 将指向基类型的指针与派生类型的指针进行比较

c - 使用多个文件指针试图在 C 中一次打开选择的文件..?