通过引用传递const指针 [英] passing const pointer by reference
问题描述
我很困惑为什么后面的代码不能编译
int foo(const float *& a){
return 0;
}
int main(){
float * a;
foo(a);
return 0;
}
编译器给出错误:
$ b b
错误:类型为'float *'的类型为'const float *&'的引用初始化无效
但是当我尝试在foo中不通过引用传递,它是编译良好。
我认为它应该显示相同的行为,不管我是否通过引用。
>
因为它不是类型安全的。请考虑:
const float f = 2.0;
int foo(const float *& a){
a =& f;
return 0;
}
int main(){
float * a;
foo(a);
* a = 7.0;
return 0;
}
任何非 - const
引用或指针必须在指向类型中是不变的,因为非< - code> const 指针或引用支持读取(协变操作)以及写入(逆变换操作)。
const
必须首先从最大间接级别添加。这将工作:
int foo(float * const& a){
return 0;
}
int main(){
float * a;
foo(a);
return 0;
}
I am confused that why following code is not able to compile
int foo(const float* &a) {
return 0;
}
int main() {
float* a;
foo(a);
return 0;
}
Compiler give error as:
error: invalid initialization of reference of type 'const float*&' from expression of type 'float*'
but when I try to pass without by reference in foo, it is compiling fine.
I think it should show same behavior whether I pass by reference or not.
Thanks,
Because it isn't type-safe. Consider:
const float f = 2.0;
int foo(const float* &a) {
a = &f;
return 0;
}
int main() {
float* a;
foo(a);
*a = 7.0;
return 0;
}
Any non-const
reference or pointer must necessarily be invariant in the pointed-to type, because a non-const
pointer or reference supports reading (a covariant operation) and also writing (a contravariant operation).
const
must be added from the greatest indirection level first. This would work:
int foo(float* const &a) {
return 0;
}
int main() {
float* a;
foo(a);
return 0;
}
这篇关于通过引用传递const指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!