Artyom Skrobov
2014-May-15 10:22 UTC
[LLVMdev] Guidance on using pointers vs. references for function arguments
Hello, Carrying on this conversation from llvm-commits:>>>> Would it be reasonable if we name both SwapByteOrder() -- it'sdifficult>>>> to describe their purpose in any other way -- and make the in-place >>>> function take a pointer, instead of a reference? >>> >>> Pointer is the wrong API: it implies having to check for null. >> >> I see that in general, the choice between pointer parameters andreference>> parameters can mean one of many things: input vs output, change ofownership>> vs no change, validity of NULL, and perhaps more. >> >> For example, Google C++ Style Guide mandates: "All parameters passed by >> reference must be labeled const. [...] it is a very strong convention in >> Google code that input arguments are values or const references whileoutput>> arguments are pointers."(http://google-styleguide.googlecode.com/svn/trunk/>> cppguide.xml#Reference_Arguments ) > > I haven't seen much of that around here. > >> I see that LLVM Coding Standards document doesn't touch this subject atall.>> Should we use this opportunity to add to it that in LLVM, the choicebetween>> pointer parameters and reference parameters is defined by whether NULL isa>> valid input? > > Not sure that's necessary, but feel free to send a proposal to llvmdev.What does the community think about such an addition? ==================================================================--- docs/CodingStandards.rst (revision 208684) +++ docs/CodingStandards.rst (working copy) @@ -837,6 +837,21 @@ It's okay to put extra implementation methods in a public class itself. Just make them private (or protected) and all is well. +Use References for Non-null Function Arguments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Using a pointer for a function argument implies that the function must treat +NULL input in a sensible way. Where such check is unpractical (e.g. when every +call site is known to pass a non-null input), or when you want to express it in +the function signature that nullptr is not a valid input, use a reference +argument instead. + +This is an application of "Use references when you can, and pointers when you +have to." maxim from the C++FAQ. Avoid using the pointers vs. references +distinction to convey other meanings, e.g. to mark the distinction between +input and output arguments, as may be advised by other style guides. + + .. _early exits: Use Early Exits and ``continue`` to Simplify Code ===================================================================