When to pass by reference and when to pass by pointer in C++?

References are easier to get right.

Is your problem with literals that you aren’t using const references? You can’t bind a temporary (produced by a literal) to a non-const reference, because it makes no sense to change one. You can bind one to a const reference.

In particular, when passing an argument to a function, and the function isn’t going to change it, and it isn’t a built-in type, pass by const reference. It works much the same as pass by value, except it doesn’t require a copy constructor call.

Pointers are useful in that they have a guaranteed invalid value you can test for. Sometimes this is irrelevant, and sometimes it’s very important. Of course, you can’t generally pass a literal by pointer, unless (in case of a string literal) it already is.

Some coding standards say that nothing should ever be passed by non-const reference, since it provides no indication at the point of call that the argument might be changed by the function. In that case, you will be required to pass by pointer. I don’t favor this, particularly as programming tools make it easier and easier to get the function signature, so you can see if a function might change an argument. However, when working in a group or for an enterprise, style consistency is more important than any individual style element.

Leave a Comment