Recently while I was explaining the basic difference between pointers and references(in context of C++ programming) to someone, I told the usual explanations which talk about different function argument passing conventions – Call by value, Call by pointer, Call by reference, and all the associated theory about references.
But then I thought whatever a C+ reference does in terms of argument passing,(Allows a memory efficient way of passing large structures/objects, at same time keeps it safe by not allowing the callee to modify any variables of the object passed as reference, if our design demands it)
A const pointer in C would achieve the same thing , e.g. If one needs to pass a structure pointer say struct mystr *ptr, by casting the structure pointer as constant –
func(int,int,(const struct mystr*)(ptr));
will ptr not be some kind of equivalent to a reference?
-
Will it not work in the way which would be memory efficient by not replicating the structure(pass by pointer) but also be safe by disallowing any changes to the structure fields owing to the fact that it is passed as a const pointer.
In C++ object context, we may pass const object pointer instead of object reference as achieve same functionality)
-
If yes, then what use-case scenario in C++, needs references.
Any specific benefits of references, and associated drawbacks?
thank you.
-AD
There are two typical use-case scenarios:
First: Pointers denote optional arguments. Since, references cannot be
NULL, but pointers can, document in the coding style that any argument that is notated as pointer, may beNULL, the function needs to handle that. Optional arguments can then be const or non-const, as can mandatory (reference) arguments.Second: References are only used in conjunction with the const keyword, because the calling syntax suggests to the reader pass-by-value semantics, which is by definition constant. Then pointers are only used for arguments that can be changed by the callee.
I personally prefer the first option, because there each of the four cases “const reference”, “non-const reference”, “const pointer”, “non-const pointer” has a different meaning. Option two only differentiates between two “things”: “function may modify that value” vs. “function will not modify that value”.