Andy wrote:
Prefer (return a reference):
char &doSomething;(Blah Blah)
To this (returning a pointer):
char *doSomething(Blah Blah)
The biggest problem with that is when you aren't returning a fundamental type. So say you return a struct or a class. You have to store that "value" to work with it, which requires a copy of that struct. With a pointer you don't have any of that overhead. Also many routines returning a pointer allocate what they return, which again saves extra memory allocation / copying in the calling routine.
There's a very good reason I don't like passing by reference (ie void func(int &n;); ) - most functions do not (and should not) modify the values that were passed to them. It is too easy to shoot yourself in the foot modifying function arguments that you forgot weren't local. When you pass pointers it becomes more obvious when you are modifying them, because you have to explicitely dereference them.
To me, passing by reference was an early (and somewhat aborted) attempt to make C an easier, more type-safe language (like Pascal), and try to hide the whole concept of the pointer from the developer. Perhaps for those working with C++ using well written classes it is possible to be totally oblivious to the fact that pointers are at work. However even then with classes it is not done by reference. Personally I don't like being oblivious to the fundamental tenets and structures of the language I'm doing hardcore development in, thus pointers (and pointers to pointers, etc) are something I use very often.
It is usually all about performance, which is something in PPC development (especially gaming) is the most critical thing.
A simple contrived example - two implementations of memcpy that copy one byte at a time:
- Code:
//Poor method
void memcpy(char *pTar, char *pSrc, int nLen) {
for (int i=0; i<nLen; i++)
pTar[i]=pSrc[i];
}
//Substantially better method
void memcpy(char *pTar, char *pSrc, int nLen) {
char *pEnd=pTar+nLen;
while (pTar<pEnd)
*pTar++=*pSrc++;
}
Of course copying one byte at a time is not the best method either way, but the second example requires less instructions in the inner loop.
Dan East