Tuesday, May 23, 2006

C++ note: references vs pointers

Use references when the target is a fixed object:

a_class* const a_inst=&a; => a_class &a_inst=a;

It's ideal to use references when passing a parameter to a function, because they probably won't move. However, when using references for return values we must be careful that the original value is in the heap and not in the stack (local varaible). It's more natural to return a pointer.

Use pointers in the cases of iterating through a lot of objects. Actually, iteration is probably the best place to use pointers. Also when the address is needed explicitly pointer is the only choice.

No comments: