#include <iostream>
void f(const int * & p)
{
int i =0;
i = p[0];
std::cout << i << std::endl;
}
int main()
{
int * p =new int[1];
p[0] =102;
f(p);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
gcc编译器为此代码提供错误:
prog.cpp: In function ‘int main()’:
prog.cpp:16: error: invalid initialization of reference of type ‘const int*&’ from expression of type ‘int*’
prog.cpp:5: error: in passing argument 1 of ‘void f(const int*&)’
Run Code Online (Sandbox Code Playgroud)
但是,如果我将"f"函数更改为
void f(const int * const & p)
Run Code Online (Sandbox Code Playgroud)
一切都好.有人可以解释为什么const表现得这样吗?谢谢.
Joh*_*itb 10
从那里int*开始const int*需要创建一个临时const int*指针并将引用绑定const int*&到该临时指针.
标准禁止为非const引用创建临时.因此,您需要在修复时创建引用const.
这是因为非const引用意味着"我想更改调用者使用该引用参数传递的参数".但是如果调用者需要转换他们的参数并最终传递一个临时值,那么引用的点是徒劳的,因此标准认为尝试传递临时值是错误的.