When should the pointer type "T * const &" be passed?

I would pass the T*& pointer when I intend to change the specified value inside the function:

 void foo(char *&p) { p = (b == true)? new char[10] : 0; } 

But I can’t get what is used for the T* const& pointer type (since this pointer is not volatile)? I mean, why shouldn't I just skip T* const ?

 void foo(char* const &p); // p is not changeable void foo(char* const p); // p is not changeable 
+4
source share
3 answers

You would use the T* const & parameter as a parameter if the value of the pointer object could be changed by something external to your function, and you would like to see changes in the value of the pointer object or if you want to save the link or pointer to a pointer object for later reading.

Parameter

A T* (equivalent to T* const as a function parameter) just gives you a copy of the pointer object, a snapshot of its value when it was passed to your function.

 void foo( char* const& ptr ) { char* p1 = ptr; // initial value global_fn(); // ptr might be changed char* p2 = ptr; // new value of ptr } 

vs

 void foo2( char* ptr ) { char* p1 = ptr; // initial value global_fn(); // ptr can't be changed, it local to this function char* p2 = ptr; // will be the same as p1 } 

Technically, even the function itself can change the value of the pointer to which the reference is transmitted.

eg.

 char* p; std::ptrdiff_t foo( char* const& ptr ) { ++p; return p - ptr; // returns 0, would return 1 if the parameter was by value } int main() { char test[] = "Hello, world!"; p = test; foo( p ); } 
+10
source

The difference is really zero. constant references are used to prevent copying of expensive copies or, in general, of uncovered types, but since pointers are trivial, this is negligible, and you can also take a value.

+3
source

I think a simpler example illustrates what Charles Bailey does. Remove the pointer problem because it doesn't matter for this question. So your question basically becomes:

 void foo(const int &p); // p is not changeable void foo(const int p); // p is not changeable 

Do you see more clearly how this works? Yes, the local variable "p" cannot be assigned in both cases. And yes, no part of the code will affect the variable in the call area. But in the previous example, p can be a reference to a variable (not const) int, which can be changed, and the latter, by an argument passed in a value that cannot be changed. (Actually, the const in the second example does not affect anything outside the function, so it is redundant. The same thing with the second example in the question.)

0
source

All Articles