Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google's style guide about input/output parameters as pointers

The Google C++ Style Guide draws a clear distinction (strictly followed by cpplint.py) between input parameters(→ const ref, value) and input-output or output parameters (→ non const pointers) :

Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers.

And further :

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers.

But I can't figure out why input/output arguments (I leave output arguments aside) should not be passed by reference. On stackoverflow there are plenty of topics related to this question : e.g. here, the accepted answer clearly say that

it's mostly about style

but that if

you want to be able to pass null, you must use a pointer

So, what's the point to always demand a pointer if I want to avoid the pointer to be null ? Why only use references for input arguments ?

like image 926
suizokukan Avatar asked Oct 18 '14 15:10

suizokukan


2 Answers

The reason for demanding that output parameters are passed as pointers is simple:

It makes it clear at the call site that the argument is potentially going to be mutated:

foo(x, y);     // x and y won't be mutated
bar(x, &y);    // y may be mutated

When a code base evolves and undergoes incremental changes that are reviewed by people who may not know the entire context all the time, it is important to be able to understand the context and impact of a change as quickly as possible. So with this style rule, it is immediately clear whether a change introduces a mutation.

like image 120
Kerrek SB Avatar answered Sep 27 '22 20:09

Kerrek SB


The point they are making (which I disagree with) is that say I have some function

void foo(int a, Bar* b);

If the b argument is optional, or it is unnecessary sometimes, you can call the function like so

foo(5, nullptr);

If the function was declared as

void foo(int a, Bar& b);

Then there is no way to not pass in a Bar.

This point (emphasis mine) is completely opinion-based and up to the developer's discretion.

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers.

If I intend for b to be an output parameter, either of the following are perfectly valid and reasonable.

void foo(int a, Bar* b);  // The version Google suggests
void foo(int a, Bar& b);  // Reference version, also perfectly fine.
like image 24
Cory Kramer Avatar answered Sep 27 '22 21:09

Cory Kramer