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.
Use references wherever you can, and pointers wherever you must.
Avoid pointers until you can't.
The reason is that pointers make things harder to follow/read, less safe and far more dangerous manipulations than any other constructs.
So the rule of thumb is to use pointers only if there is no other choice.
For example, returning a pointer to an object is a valid option when the function can return nullptr
in some cases and it is assumed it will. That said, a better option would be to use something similar to std::optional
(requires C++17; before that, there's boost::optional
).
Another example is to use pointers to raw memory for specific memory manipulations. That should be hidden and localized in very narrow parts of the code, to help limit the dangerous parts of the whole code base.
In your example, there is no point in using a pointer as an argument because:
- if you provide
nullptr
as the argument, you're going in undefined-behaviour-land;
- the reference attribute version doesn't allow (without easy-to-spot tricks) the problem with 1.
- the reference attribute version is simpler to understand for the user: you have to provide a valid object, not something that could be null.
If the behaviour of the function would have to work with or without a given object, then using a pointer as an attribute suggests that you can pass nullptr
as the argument and it is fine for the function. That's kind of a contract between the user and the implementation.
Best Answer
A reference is basically a pointer with restrictions (has to be bound on creation, can't be rebound/null). If it makes sense for your code to use these restrictions, then using a reference instead of a pointer allows the compiler to warn you about accidentally violating them.
It's a lot like the
const
qualifier: the language could exist without it, it's just there as a bonus feature of sorts that makes it easier to develop safe code.