Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing const pointer by reference

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,

like image 267
ravi Avatar asked Jul 17 '12 00:07

ravi


People also ask

Can pointers be passed by reference?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

How do you pass a constant reference in C++?

The rules for initializing references make passing by reference-to-const an efficient and attractive alternative to passing by value. As in C, function calls in C++ normally pass arguments by value. For example, given: int abs(int i);

Can you modify a const reference C++?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.


1 Answers

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;
}
like image 146
Ben Voigt Avatar answered Oct 01 '22 13:10

Ben Voigt