C++中"int* const&x"和"int* const x"之间的区别



我读过通过值传递、通过引用传递和通过常量引用传递(指针(之间的区别,但我不理解后者与仅传递常量指针之间的区别。举个例子,之间有什么区别

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() {
}

这两者都会导致相同的CCD_ 1。

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

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;
}

最新更新