Use references when you can, and pointers when you need to. Reasons you'd need to use a pointer:
- There might not be an object for it to point at (null pointer, no null references).
- You might need to refer to different objects during its lifetime.
- You might need to refer to a whole array of objects (but
std::vector
is usually better).
There are, however, cases where the usage of the two doesn't really overlap at all, and you simply can't substitute one for the other. For one obvious example, consider the following code:
template
size_t size(T(&matrix)[N]) {
return N;
}
This allows you to find the size of an array:
int array1[some_size];
int array2[some_other_size];
size_t n = size(array1); // retrieves `some_size`
size_t m = size(array2); // retrieves `some_other_size`
...but it simply won't compile if you try to pass a pointer to it:
int *x = new int[some_size];
size_t n = size(x); // won't compile
At very best it seems to make little sense to write the code to receive a pointer when part of its point is to reject being passed a pointer.