TITLE: how efficient are references vs pointers (Newsgroups: comp.lang.c++.moderated) CLAMAGE: clamage@taumet.Eng.Sun.COM (Steve Clamage) >> Reference paramters and return types for functions are often >> useful for several reasons: they avoid copying an object and >> they can simplify syntax, for example. SRINIVAS: Srinivas Vobilisetti >I guess, at the same time, they make programs more cryptic. When >we are browsing the code, we are not sure if a variable is going to >be changed in a function at the point of its invocation (non-const >reference argument) or not (const reference or value argument). But >when we use pointers, we have hint that the value of the object may >be changed at the point of function invocation. CLAMAGE: 30 Aug 1996 But if the pointer argument is pointer-to-const, the function should be expected not to change the actual argument. So you still don't know until you look at the function declaration. If you are writing new code, you have no business calling a function if you don't know what its interface is. If you are reading code written by someone else, either it matters whether the function modifies its argument or it doesn't. If it does matter, you have to look at its interface definition regardless. SRINIVAS: >I know, pointers require two time memory access (once for the >address and next for the value). But Micheal Daconta says, If >I understand it right and I apologize otherwise, that references >are not pointers but are symbol table alias entries and hence >require one time memory access. If this true, I guess, we can >use references to increase run-time efficiency. CLAMAGE: It can happen that a reference is more efficient than a pointer under some restricted circumstances, but normally the code generated for either is identical. The semantics of references in C++ virtually require that they be implemented the same way as pointers, although the language definition deliberately avoids specifying implementations. Daconta may have been thinking of a case like this: extern int K; int& R = K; At this point, the compiler can substitute K for all uses of R. I don't know whether many (or any) compilers do so, and it also seems to me that this situation is pretty infrequent. The pointer equivalent would be extern int K; int* const R = &K; At this point, the compiler can substitute &K for most uses of R, and K for all uses of *R. It seems to me that a compiler that would make the substitution for references would also make the substitution for pointers. The same sort of analysis serves both cases. But if a function has a reference argument and is called from different places in the program with different actual arguments (surely the most common situation for references), I don't believe a compiler could do anything more efficient than implement the calls the same way it would for pointer arguments.