Special Hot Alien ?! ;-)

reference vs pointer in C++

28 Aug 2016

Some opinions about refereces vs pointers.

My rule of thumb is:

There are following differences between pointers and references.

Taking those into account my current rules are as follows.

A function uses passed data without modifying it:

From C++ FAQ Lite -

Use references when you can, and pointers when you have to.

References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside. The exception to the above is where a function’s parameter or return value needs a “sentinel” reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references must always alias objects, not a dereferenced NULL pointer).

Note: Old line C programmers sometimes don’t like references since they provide reference semantics that isn’t explicit in the caller’s code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.

Original source: http://stackoverflow.com/questions/7058339/when-to-use-references-vs-pointers

Tweet
comments powered by Disqus