When should I use pointers instead of references in API-design?

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:

  1. if you provide nullptr as the argument, you’re going in undefined-behaviour-land;
  2. the reference attribute version doesn’t allow (without easy-to-spot tricks) the problem with 1.
  3. 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.

Leave a Comment

techhipbettruvabetnorabahisbahis forumuedusedueduedueduseduedueduseduedu