Re: Passing a reference to a std::map
On Mon, 23 Feb 2009 17:29:21 -0500, Joseph M. Newcomer
<newcomer@flounder.com> wrote:
I find it a common error that people think they have to pass pointers-to-objects because
when they learned C they always passed pointers-to-objects. As you point out, a reference
parameter is far better, and eliminates all the problems.
joe
The usual argument is that saying f(&x) makes it clearer that f may modify
x. I've always called this the "call-site clue", and long-time C
programmers often think it's really valuable. I know I did six months or so
into C++, and then I realized it's pretty useless. When using pointers
pervasively to simulate pass by reference, you often end up with f(x), with
x being a pointer, and this tells you nothing about what could happen to
*x, which is what is interesting. So you have to look at the documentation
or at least the function declaration to see what's going on, which defeats
the superficial scanning f(&x) is supposed to enable. In this light, it
became apparent that superficial scanning isn't the best goal in the world,
and then I realized I never did it anyway. I started using references
instead of pointer parameters as my default, and I started using pointers
only for optional arguments, to indicate a transfer of ownership, and when
writing C-style functions that work on arrays; I stopped using pointers to
indicate an argument may be modified. Lots of people have reached similar
conclusions. I've always found this interesting, because it's a good
example of something that was "obviously" valuable but never really was,
and it only seemed so because it was familiar and the only option available
in what was learned first.
--
Doug Harrison
Visual C++ MVP