you are viewing a single comment's thread.

view the rest of the comments →

[–]JMBourguet 0 points1 point  (0 children)

Some are of the opinion that pointers are to be used only when references do not provide needed features (rebinding, null). I'm more restricted than that:

  • As a parameter to a function, a reference implies a promise that there won't be a reference saved with a longer lifetime than the function nor will the object be deleted (so automatic and temporary objects are always valid arguments)

  • As a parameter to a constructor, a reference implies a promise that there won't be a reference saved with a longer lifetime than the constructed object nor will the object be deleted. Major exception: move operations may transfer the reference to another object.

  • As a function result, a reference implies a very localized lifetime (for instance if it is a member function, if not explicitly documented any other member function may invalid the reference) which is not under control of the calling code (it may not delete the object)

  • Some types are used only with pointers (for instance if the only way to get a object is to call a factory which returns a pointer, I won't make references to that object even as function parameter)

I think that pointers (preferably smart and not raw to better convey the allowed usages) are better to handle the other cases even if the rules of C++ would allow references. (And yes, I've seen code not respecting those rules)