passing const pointer by reference

旧街凉风 提交于 2019-12-20 12:05:37

问题


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,


回答1:


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


来源:https://stackoverflow.com/questions/11514688/passing-const-pointer-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!