Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid non-const reference parameters [duplicate]

Tags:

c++

I come across this output param convention, which favours pointers than references.

"Within function parameter lists all references must be const:

void Foo(const string &in, string *out);

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters except when required by convention, e.g., swap()."

That seems somewhat different to the accepted answer to this question, which says references should be used instead, unless the function involves some pointer arithmetic.

So I wonder if this input param is const reference, output param is pointer is just a matter of google-style, or it is a more generally accepted practice (to avoid non-const reference parameters).

like image 574
artm Avatar asked Jul 26 '15 01:07

artm


Video Answer


1 Answers

You don't mention the rationale for this coding practice. The main reason I'm aware of is that it makes it clearer what's getting written when you scan your eyes over a block of code. Even if you don't remember exactly what every called function does, you can still tell when a variable is being modified, because you'll see its address being passed.

Also, changing a function to sometimes modify one of its parameters can't silently break other code. You have to go to every call site and call by pointer. Presumably you'll notice if one of the call sites needs you to not change that parameter there.

I can't speak to how widely adopted or loved this convention is, but that is the reasoning behind it, as far as I'm aware.

It can potentially lead to slightly less optimal compiler output. A call-by-reference means that callers can assume that only the actual variable was modified, and no pointer-arithmetic was done to modify other elements of the same array. (Unless you have cross-file compilation, the compiler can't know the pointer arg to the called function isn't treated as an array.)

like image 69
Peter Cordes Avatar answered Nov 07 '22 03:11

Peter Cordes