#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;
}
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*&)’
但如果我将“f”功能改为
void f(const int * const & p)
一切都好。有人可以解释为什么const表现得这样吗?感谢。
答案 0 :(得分:10)
从int*
转到const int*
需要创建一个临时const int*
指针,并将引用const int*&
绑定到该临时值。
标准禁止为非const引用创建临时文件。因此,您需要在修复时创建引用const。
这是因为非const引用意味着“我想更改调用者使用该引用参数传递的参数”。但是如果调用者需要转换他们的参数并最终传递一个临时值,那么引用的点是徒劳的,因此标准认为尝试传递临时值是错误的。
答案 1 :(得分:1)
如果允许第一次转换(int *
到const int * &
),那么你可以编写一个像这样的邪恶函数:
const int really_const[] = {1,2,3};
void evil(const int * & p)
{
p = really_const;
}
int main()
{
int not_const[3];
int * p = not_const;
evil(p);
p[0] = 0; // Whoops: modifying a const object
}
第二次转换很好,因为它会阻止函数以这种方式修改指针。