Passing args as a reference to a pointer with (no) constness gives different addresses

void f(char * & pch) { cout << &pch << " " << pch << endl; } int main() { char *pch2 = new char[11]; strcpy(pch2, "1234567890"); cout << &pch2 << " " << pch2 << endl; f(pch2); return 0; } 

gives the following conclusion:

 0xbfa0d62c 1234567890 0xbfa0d62c 1234567890 

but if I changed the first line as follows

 void f(char const * const & pch) { 

i will receive:

 0xbfec7df8 1234567890 0xbfec7dfc 1234567890 

Is the difference in pointers due to the need to mark the new memory cell as const or something else?

+4
source share
2 answers

pch2 is a char* , not a char const* . You cannot bind a link of type char const*& to a pointer of type char* , so the following will be poorly formed:

 char* p(0); char const*& r(p); 

Similarly, if your function was declared as void f(char const*& pch) , you would not be able to call it with the char* argument due to a const-qualifier mismatch.

The reason your example works is because the const link can bind to a temporary one, and the compiler can create a temporary copy of your char* pointer, specify a temporary char const* type, and bind the pch link to this temporary pointer.

+5
source

In the first case, the parameter is an exact match to the parameter of the function, so it can be attached directly to the link.

In the second case, the types are different (slightly), so the compiler creates a temporary one that is passed to the function.

+2
source

Source: https://habr.com/ru/post/1383698/


All Articles