Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

When to use references vs. pointers

I comprehend the syntax and general semantics of pointers versus references, however how might I choose when it is pretty much suitable to utilize references or pointers in an API?

Normally a few circumstances need either (operator++ needs a reference contention), yet overall I'm discovering I like to utilize pointers (and const pointers) as the syntax is certain that the variables are being passed destructively.

For example in the accompanying code:

void add_one(int& n) { n += 1; }
void add_one(int const n) { n += 1; }
int main() {
int a = 0;
add_one(a); // Not clear that a may be modified
add_one(&a); // 'a' is clearly being passed destructively
}


With the pointer, it's consistently (more) clear what's happening, so for APIs and such where clarity is a major concern are pointers not more proper than references? Does that mean references ought to possibly be utilized when essential (for example operator++)? Are there any exhibition worries with either?
by

2 Answers

rahul07
Use pointers for outgoing or in/out parameters. So it can be seen that the value is going to be changed. (You must use &)
Use pointers if NULL parameter is acceptable value. (Make sure it's const if it's an incoming parameter)
Use references for incoming parameter if it cannot be NULL and is not a primitive type (const T&).
Use pointers or smart pointers when returning a newly created object.
Use pointers or smart pointers as struct or class members instead of references.
Use references for aliasing (eg. int &current = someArray[i])
pankajshivnani123
The performances are exactly the same, as references are implemented internally as pointers. Thus you do not need to worry about that.

There is no generally accepted convention regarding when to use references and pointers. In a few cases you have to return or accept references (copy constructor, for instance), but other than that you are free to do as you wish. A rather common convention I've encountered is to use references when the parameter must refer an existing object and pointers when a NULL value is ok.

Some coding convention (like Google's) prescribe that one should always use pointers, or const references, because references have a bit of unclear-syntax: they have reference behaviour but value syntax.

Login / Signup to Answer the Question.