passing const pointer by reference

前端 未结 1 1707
误落风尘
误落风尘 2021-02-04 06:26

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         


        
1条回答
  •  北海茫月
    2021-02-04 07:20

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

    0 讨论(0)
提交回复
热议问题