c++ - C++中 `int* const& x`和 `int* const x`之间的区别

标签 c++ pointers reference

我已经读过按值传递、按引用传递和按常量引用传递(指针)之间的区别,但我不明白后者与仅传递常量指针之间的区别。举个例子,有什么区别

int PI = 3;

int* getArg(int* const& x){
    x = Π
    return x;
}

int main() {

}

int PI = 3;

int* getArg(int* const x){
    x = Π
    return x;
}

int main() {

}

这两者都会导致相同的错误:分配只读参数“x”

最佳答案

如果您清楚按值和按引用传递变量,请尝试将复杂类型分解为多个部分,以帮助理解正在发生的情况:

using PointerToInt = int*;
using ConstPointerToInt = PointerToInt const;

int* getArg_v1(ConstPointerToInt x) {
    x = Π  // it's const by value so you're not allowed to change it
    return x;
}

int* getArg_v2(ConstPointerToInt& x) {
    x = Π  // it's const by reference so you're not allowed to change it
    return x;
}

关于c++ - C++中 `int* const& x`和 `int* const x`之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66785156/

相关文章:

c4133 警告 C 代码

c++ - 为什么从 lambda 返回 const 引用会导致临时引用?

c++ - 我可以在windows下使用glibc吗?

c++ - C++程序中多个源文件中的相同头文件

c - 使用 extern struct 或 extern pointer to struct 的最佳实践?

c++ - 来自具有结构的 vector 的对象

c# - 为什么此处需要引用未使用的程序集

c - 为什么此引用不起作用/无效?

c++ - OpenGL 纹理映射空白屏幕

c++ - 编译器确定给出或省略参数