繁体   English   中英

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

[英]Difference between `int* const& x` and `int* const x` in C++

我已经阅读了按值传递、按引用传递和通过常量引用传递(指针)之间的区别,但我不明白后者之间的区别,只是传递一个常量指针。 例如,两者之间有什么区别

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

}

这两者都会导致相同的error: assignment of read-only parameter '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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM