Reputation: 451
Why does c++ not compile the following?
void func(const int *&pp)
{
//Do stuff
}
int main()
{
int var =23;
int* ptr_to_var = &var;
func(ptr_to_var);
}
To clarify I want to pass a pointer as reference to a function, but the pointer should not be changed in the function hence the const.
The compile warning I get is:
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
I could do something like this:
void func(int **pp)
{
//Do stuff
}
But this doesn't give me the exact behavior I would want as now I can actually change the location where the pointer points to, i.e. I miss the const key word.
If you would then do:
void func(const int **pp)
{
//Do stuff
}
This doesn't compile either and I'm actually not sure that if it would compile it would actually do what I want.
Upvotes: 1
Views: 82
Reputation: 238311
Why does c++ not compile the following?
void func(const int *&pp) { //Do stuff }
This is well-formed, and any standard conforming compiler will compile it.
The compile warning I get is:
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
The error message isn't very clear, but I think it is trying to say that you tried to initialise the reference with an rvalue. References to non-const lvalues cannot be bound to rvalues.
If you would then do:
void func(const int **pp) { //Do stuff }
This doesn't compile either
This is also well-formed, and a standard conforming compiler must accept it.
You can see both examples succesfully compiling here.
Upvotes: 3