2

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

as df
  • 29
  • 6
  • 1
    Related, but takes the angle of "how to circumvent", rather than "why": [Cannot convert argument from int * to const int *&](https://stackoverflow.com/questions/39345996/) – JaMiT Mar 22 '22 at 02:09
  • *"But i used const."* -- this makes me think that [What is the difference between `const int*`, `const int * const`, and `int const *`?](https://stackoverflow.com/questions/1143262/) might be relevant. – JaMiT Mar 22 '22 at 02:29
  • @JaMiT ty for answer it helped me! – as df Mar 22 '22 at 03:14
  • Consider what could happen if you allowed it: `const int x = 0; void f(const int*& y) { y = &x; } int main() { int* p = nullptr; f(p); *p = 1234; }`. Oops, assigning to a const object. – molbdnilo Mar 22 '22 at 09:59

1 Answers1

5
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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405