|
Boost : |
From: Jon Kalb (jonkalb_at_[hidden])
Date: 2001-12-27 18:49:18
> -----Original Message-----
> From: Beman Dawes [mailto:bdawes_at_[hidden]]
> Sent: Thursday, December 27, 2001 2:23 PM
> To: boost_at_[hidden]
> Subject: [boost] Re: naming convention
>
>
> At 02:10 PM 12/27/2001, Paul Beardsley wrote:
> >3. A few years ago when I started C++, someone told
> >me about the convention that arguments to class
> >methods or functions are (a) const references for the
> >read-only arguments, and (b) non-const pointers for write
> >arguments.
>
> I think the more usual rule-of-thumb is something like:
>
> (a) read-only arguments: by value for builtin types,
> otherwise by const
> reference.
> (b) arguments written to: by reference
>
> Some people add something like
>
> (c) If a pointer or reference is to be stored for later use,
> pass it as a
> pointer to emphasize the usage. If ownership is involved,
> pass it wrapped
> in some kind of smart pointer.
>
> I expect Scott Meyers Effective C++ / More Effective C++
> books would deal
> with the issues in detail.
I believe the policy that Paul refers to is Bjarne's. On page 99 of the
Special Edition of TC++PL he says:
"To keep a program readable, it is often best to avoid functions that
modify their arguments. Instead, you can return a value from the
function explicitly or require a pointer argument: <code examples
omitted> ... Consequently "plain" reference arguments should be used
only when the name of the function gives a strong hint that the
reference argument is to be modified."
One feature of C that is lost in C++ is the ability to read calling code
and to know what is not modified. If one follows this policy (and does
the right things when overloading operators), then this feature is not
lost in C++.
My experience has been that most people tend to use the rules outline by
Beman above with a possible additional rule:
(d) Use pointer arguments for "optional" parameters.
An example of this is std::time() which takes a pointer to std::time_t.
If the pointer is non-null, the value of the time_t to which it points
is modified, otherwise the parameter is ignored. When working with code
that follows this policy it is always safe to pass 0 for pointer
arguments because if a function must have a particular parameter it will
be a reference.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk