references and pointers

M

MQ

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?

regards,
B.
 
J

Juha Nieminen

MQ said:
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.
 
B

borophyll

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
 
I

Ian Collins

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"
He made a mistake? Or possibly idiomatic style has changed over time.
 
B

borophyll

He made a mistake? Or possibly idiomatic style has changed over time.

Are you serious? This is in the most recent version of "The C++
programming language", and he mentions this point in several
locations. Hardly an editing mistake. Let me just state that I am
not debating that the point he makes seems right, it does not seem
right to me, but it seems to be more than just a mistake.
 
I

Ian Collins

*Please* don't quote signatures.
Are you serious? This is in the most recent version of "The C++
programming language", and he mentions this point in several
locations. Hardly an editing mistake. Let me just state that I am
not debating that the point he makes seems right, it does not seem
right to me, but it seems to be more than just a mistake.
http://www.research.att.com/~bs/bs_faq2.html#pointers-and-references

Puts a different view across, so one of my guesses was probably true.

I'd only recommend using pointers when the argument can meaningfully be
NULL, or when interfacing with legacy code.
 
T

Tim H

I'd only recommend using pointers when the argument can meaningfully be
NULL, or when interfacing with legacy code.

Or when you need to store a "reference" (for lack of a better term) to
a shared object in a class that must be STL container-compatible
(assignable).

I admit that I am newish to C++, but the pattern I have found is that
I only use references when passing arguments. I try hard never to use
"out" variables, but when I do, I use pointers.
 
J

Jim Langston

Ian Collins said:
*Please* don't quote signatures.
http://www.research.att.com/~bs/bs_faq2.html#pointers-and-references

Puts a different view across, so one of my guesses was probably true.

I'd only recommend using pointers when the argument can meaningfully be
NULL, or when interfacing with legacy code.

I was actually debating this with myself 2 days ago. Someone gave me some
code work on, he was using pointers to modify the parameters. I started to
change them to references, then realized that in mainline, there is no
indication if the parameter was going to be changed or not.

Consider.

void foo( int* Val )
{
*Val = 23;
}

void bar( int& Val )
{
Val = 23;
}

int main()
{
int MyInt = 10;
foo( &MyInt );
bar( MyInt );
}

Becaue Foo forces us to take the address of MyInt, it is fairly obvious in
mainline that MyInt is probably going to be changed, else why pass the
address of a simple int? bar however gives no indication in mainline that
MyInt will be changed.

Maybe that is the reasoning behind it.

Reguardless, I did go ahead and change them all to references anyway.
 
I

Ian Collins

Jim said:
I was actually debating this with myself 2 days ago. Someone gave me some
code work on, he was using pointers to modify the parameters. I started to
change them to references, then realized that in mainline, there is no
indication if the parameter was going to be changed or not.

Consider.

void foo( int* Val )
{
*Val = 23;
}

void bar( int& Val )
{
Val = 23;
}

int main()
{
int MyInt = 10;
foo( &MyInt );
bar( MyInt );
}

Becaue Foo forces us to take the address of MyInt, it is fairly obvious in
mainline that MyInt is probably going to be changed, else why pass the
address of a simple int? bar however gives no indication in mainline that
MyInt will be changed.
A good example of why you should give functions meaningful names.
 
K

Kira Yamato

I was actually debating this with myself 2 days ago. Someone gave me some
code work on, he was using pointers to modify the parameters. I started to
change them to references, then realized that in mainline, there is no
indication if the parameter was going to be changed or not.

Consider.

void foo( int* Val )
{
*Val = 23;
}

void bar( int& Val )
{
Val = 23;
}

int main()
{
int MyInt = 10;
foo( &MyInt );
bar( MyInt );
}

Becaue Foo forces us to take the address of MyInt, it is fairly obvious in
mainline that MyInt is probably going to be changed, else why pass the
address of a simple int? bar however gives no indication in mainline that
MyInt will be changed.

Maybe that is the reasoning behind it.

Reguardless, I did go ahead and change them all to references anyway.

I think you made a good call to change them to references anyway.
Otherwise, you would have to worry about people passing invalid pointer
like in foo(0).

So, like Ian Collins had stated in another post, use pointers only if
there is a need to include NULL as a possible value. But even in that
case, perhaps it is cleaner for the class to implement a singleton
object that represents the "NULL" object of the class anyway.

I'm still a newbie in C++, but I'm getting the sense that proper use of
STL should eliminate all needs of pointers. However, for efficiency
purposes, perhaps pointers should sometimes be employed, just like
'goto' is theoretically not needed but may be practically needed.
 
B

Bo Persson

(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

Could you give some context to this statement, like the section number
or something?

It could be that he argues about const against non-const arguments.
Instead of modifyng some part of an argument, like a struct, the
function might be better off just returning the new value.


Bo Persson
 
P

peter koch

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.

/Peter
 
K

Kai-Uwe Bux

peter said:
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.


Best

Kai-Uwe Bux
 
P

pauldepstein

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.

Best

Kai-Uwe Bux- Hide quoted text -

- Show quoted text -

The advice seems a bit odd because most elementary texts have a swap-
two-integers problem, and the intended solution is always to use int&
variables -- pointer-to-int are not mentioned in the standard
solution.

Intended solution is to use void swap(int& x, int& y)

This function creates a local tmp variable whose value = x and then
sets x=y, y = tmp. The result is that y now contains the value x held
and x contains the value y held.

Paul Epstein
 
B

Bo Persson

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
 
G

Guest

Are you serious? This is in the most recent version of "The C++
programming language", and he mentions this point in several
locations. Hardly an editing mistake.

The latest edition is still almost 10 years old and written when the
standard was new. I would expect that the idioms have developed a bit
since then.

While I can agree that having to take the address of the arguments makes
it more explicit. But on the other hand you should never call a function
unless you know what effects it is going to have. And since you cannot
indicate the side effects of a function in the signature you must thus
look in the documentation anyway.

My policy regarding the use of pointers and references is to use
references when I can and pointers when I must.
 
T

Tristan Wibberley

The latest edition is still almost 10 years old and written when the
standard was new. I would expect that the idioms have developed a bit
since then.

Barne Stroustrup mustn't have had any input into the codecvt facet
then :)

--
Tristan Wibberley

Any opinion expressed is mine (or else I'm playing devils advocate for
the sake of a good argument). My employer had nothing to do with this
communication.
 
J

Juha Nieminen

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

Even though he is the creator of the language, that still sounds like
a question of opinion, a question of style.

IMO functions taking references should *always* take const references
for parameters they do not modify, and only take non-const references
for parameters they might modify. Thus, as a rule of thumb, if you are
calling a function which takes a non-const reference you must assume
that it may change it.

Of course there may be badly-designed third-party C++ libraries which
take non-const references even though they never modify them, but OTOH
even if they took pointers that wouldn't change anything: You still
couldn't be certain whether the function modifies it or not. You must
assume that it may.
 
P

Paavo Helde

[...]
I'm still a newbie in C++, but I'm getting the sense that proper use
of STL should eliminate all needs of pointers. However, for
efficiency purposes, perhaps pointers should sometimes be employed,
just like 'goto' is theoretically not needed but may be practically
needed.

References are usually implemented by pointers anyway, so there is no
efficiency gain (except that you don't (shouldn't) need to check for
NULL-ness, but that's more a design issue and costs next to nothing
anyway on current hardware).

Pointers are not good for out parameters IMHO, because pointers can be
NULL. If I call some function for retrieving some data and passing NULL
pointer, what I'm saying? Do I want to get this data after all or not? If
not, why I call this function? I should call another function or overload
instead if I don't want to get any data back. In case of references I am
obliged to provide the space for data and the meaning of the operation is
much clearer.

You are right that raw pointers should generally not be used in C++ code.
If pointer semantics are required, for example for storing in STL
containers, some kind of smartpointers should be used instead.


Paavo
 
J

James Kanze

[...]
I'm still a newbie in C++, but I'm getting the sense that
proper use of STL should eliminate all needs of pointers.

Where did you get this idea from? Iterators can only be used
for objects in a sequence---in practice, in a container. Most
objects aren't in a container; entity objects never are, since
they aren't copiable, and it's rare to need a pointer for
anything but an entity object.
However, for efficiency purposes, perhaps pointers should
sometimes be employed, just like 'goto' is theoretically not
needed but may be practically needed.

'goto' is never needed, even practically. Pointers are almost
always needed, even theoretically. (I say almost, because I
believe that there are applications which don't have any
"entity" objects. I can imagine some serious numeric
applications, for example, which use neither pointers nor
iterators, ever.)

Iterators are for iterating. For the most part, you don't want
to maintain iterators (nor pointers to objects in a container)
for any significant duration; adding or removing elements from
the container can invalidate the iterators. STL containers are
designed with value semantics (the only semantics which really
make sense for a container in the context of C++). This means
that objects in the container do not have identity; they may
"move around". It also means that, conceptually, you won't
normally keep pointers, references or iterators designating them
beyond the scope of a simple algorithm or iteration. If you
find yourself doing so, then you're using the wrong tool, or
misusing it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top