Search code examples
c++referenceconstants

C++) why const int*& parameter can't take int* argument?


before writing, I'm not good at english. So maybe there are many awkward sentence.

void Func1(const int* _i) {  };
void Func2(const int& _j) {  };
void Func3(const int* (&_k)) {  };
int main() 
{
    int iNum = 1; 
    int* pInt = new int(1); 
    Func1(pInt); // works; 
    Func2(iNum); //works 
    Func3(pInt); // error 
} 

I use Visual Studio and error message said "Cannot convert argument 1 from 'int *' to 'const int *&'"

I know it cant convert because of '&'. _i equals pInt so it may change dereference. But i used const. so i think it will work but const keyword doesnt work. why const keyword doesnt work unlike other cases? ex)Func1,Func2


Solution

  • Func1(pInt); // works; int* could convert to const int* implicitly
    Func2(iNum); //works; int could be bound to const int&
    Func3(pInt); // error;
    

    pInt is a int*, when being passed to Func3 which expects a reference to const int*, then it would be converted to const int*, which is a temporary and can't be bound to lvalue-reference to non-const like const int* & (lvalue-reference to non-const pointer to const int).

    If you change the parameter type of Func3 to int* &, then no conversion is required, pInt could be bound directly. Or change to const int* const & (lvalue-reference to const pointer to const int) or const int* && (rvalue-reference) which could bind to temporary.