Pointer vs. Reference
Solution 1:
My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
Solution 2:
I really think you will benefit from establishing the following function calling coding guidelines:
-
As in all other places, always be
const
-correct.- Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the
const
specifier.
- Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the
-
Only pass a value by pointer if the value 0/NULL is a valid input in the current context.
Rationale 1: As a caller, you see that whatever you pass in must be in a usable state.
Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value.
Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can.
-
If a function argument is an out-value, then pass it by reference.
- Rationale: We don't want to break item 2...
-
Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy.
- Rationale: Avoid unnecessary copies.
- Note: small enough and cheap enough are not absolute measurables.