Kai-Uwe Bux wrote:
:: peter koch wrote:
::
::: On 4 Nov., 02:38, (e-mail address removed) wrote:
::::
::::
::::
::::
::::
::::: MQ wrote:
:::::: Can someone tell me where I should use pointers and where I
:::::: should use
:::::: references? In his book, Stroustrup says that you should use
:::::: pointers
:::::: for passing arguments that are to be modified, not references.
:::::: Yet, in an interview, he laments the overuse of pointers and
:::::: such in code. It seems contradictory to me. Why should we not
:::::: use references instead of pointers? Can someone give me an
:::::: idea of best practices in this respect?
::::
::::: Think about the basic difference between references and
::::: pointers: Pointers can be made to point to something else than
::::: what they were initialized to point to (including null) while
::::: references can't.
::::
::::: This, IMO, gives a good rule of thumb for the decision: If
::::: you don't need to change where the thing is pointing, use
::::: references, else use pointers.
::::
:::: Why then does Stroustrup make the following statement in his
:::: book:
::::
:::: "Be suspicious of non-const reference arguments; if you want the
:::: function to modify its arguments, use pointers and value return
:::: instead"
::::
:::: This says to me that we in fact should *not* use references in
:::: this way- Skjul tekst i anførselstegn -
:::
::: Where does he write that? I've read that book and certainly would
::: have remembered that statement, so I believe you must be
::: misunderstanding him.
::
:: See section 7.9, point [1] in the list of advice. There is
:: virtually no context to the sentence that could change the literal
:: interpretation.
::
Interesting!
Point 1 also refers to §5.5 where he writes (p 99 in my 5th printing):
"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.
[some code example]
The increment(x) notation doesn't give a clue to the reader that x's
value is being modified, the way x=next(x) and incr(&x) does.
Consequently 'plain' reference arguments should be used only where the
name of the function gives a strong hint that the reference argument
is modified."
That's pretty literal!
So most of us agree that a function should not modifiy its argument,
unless that is clear from the function's name. Generally, a function
name should always tell what the function does. Using a pointer
argument doesn't really solve this problem.
Sometimes even Bjarne gives advice that are not that good.
Bo Persson