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