Re: Don't pass by reference to non-const?
* Sousuke:
I'm having doubts about the validity of the following guideline:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Reference_Arguments#Reference_Arguments
For some reason I haven't noticed whether this is generally followed.
Is it? Or is it just something made up at Google? What do you think of
it?
Please quote the guideline you refer to.
<quote>
Reference Arguments
All parameters passed by reference must be labeled const.
Definition: In C, if a function needs to modify a variable, the parameter must
use a pointer, eg int foo(int *pval). In C++, the function can alternatively
declare a reference parameter: int foo(int &val).
Pros: Defining a parameter as reference avoids ugly code like (*pval)++.
Necessary for some applications like copy constructors. Makes it clear, unlike
with pointers, that NULL is not a possible value.
Cons: References can be confusing, as they have value syntax but pointer semantics.
Decision:
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.
One case when you might want an input parameter to be a const pointer is if you
want to emphasize that the argument is not copied, so it must exist for the
lifetime of the object; it is usually best to document this in comments as well.
STL adapters such as bind2nd and mem_fun do not permit reference parameters, so
you must declare functions with pointer parameters in these cases, too.
</quote>
I.e. Google would design std::getline with pointer argument.
It sounds political.
From a non-political perspective it's pretty stupid since it requires extra
notation and requires unnecessary bug-vectors, both something you would
absolutely not want in the code, but presumably that "decision" made sense in
some workplace politics, something with not too disturbing consequences that
some group was very opposed to but had to accept; you're the boss, man.
Cheers,
- Alf (telepathic circuit engaged)