c++ - 通过引用传递 const 指针

标签 c++ reference constants implicit-conversion pointer-conversion

我很困惑为什么以下代码无法编译

int foo(const float* &a) {
    return 0;
}
int main() {
    float* a;
    foo(a);

    return 0;
}

编译器给出错误:

error: invalid initialization of reference of type 'const float*&' from expression of type 'float*'

但是当我尝试在 foo 中不通过引用传递时,它编译得很好。

我认为无论我是否通过引用传递,它都应该显示相同的行为。

谢谢

最佳答案

因为它不是类型安全的。考虑:

const float f = 2.0;
int foo(const float* &a) {
    a = &f;
    return 0;
}
int main() {
    float* a;
    foo(a);
    *a = 7.0;

    return 0;
}

任何非const引用或指针在指向的类型中都必须是不变,因为非const指针或引用支持读取(协变操作)和写入(逆变操作)。

const 必须首先从最大间接级别添加。这会起作用:

int foo(float* const &a) {
    return 0;
}
int main() {
    float* a;
    foo(a);

    return 0;
}

关于c++ - 通过引用传递 const 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514688/

相关文章:

c++ - 将非指针变量作为对指针的引用传递给函数

c++ - libuvc 和 opencv2 的 G++ undefined reference

c++ - 将 const this 传递给接受 const 指针的函数不是 const 正确的吗?

php - 从表达式创建 PHP 类常量的最佳解决方法?

c++ - Boost.uBLAS 中的矩阵表达式和 vector 表达式类是什么?

c++ - 继承成本是多少?

c++ - 没有运算符 "<<"匹配这些操作数(可变长度数组)

C++ opencv 访问像素值不正确

c# - 在 UWP 应用程序中使用 WPF dll

c - 在 C 中定义常量之间的依赖关系?