473,327 Members | 2,007 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

C++: can someone explain to me, a C/Hw guy, what the diff is between a reference (&) and a pointer?

bo
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA

Jul 22 '05 #1
14 2498

"bo" <bo@cephus.com> wrote in message
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...


http://www.parashift.com/c++-faq-lit...s.html#faq-8.6

Sharad
Jul 22 '05 #2
bo wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

References are more easy to be optimised out.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #3
Sharad Kala wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.

Do you consider it useful?

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #4

"Ioannis Vranos" <iv*@guesswh.at.grad.com> wrote in message > Sharad Kala
wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.
Do you consider it useful?


Well, I think they could have been little more clearer (considering it's
FAQ). Basically references are preferred when one knows that one needs to
refer to the same object and that won't change. In fact it's quite possible
that compilers implement references in terms of T* const. Also references
offer the advantage that you don't need to check for null-ness so many if
loops are avoidable.

Sharad


Jul 22 '05 #5
bo posted:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some actual difference that makes references different and or preferable over pointers in some cases...

TIA

References are nicer to work with, in that they behave
exactly like real variables.

Pointers are... different...

As I always I prefer the more familiar. Here's what I do:

A) Use a references. If I can't... go to plan B.

B) Use a pointer.
The only advantage references have over pointers is that
they behave exactly like your familiar variables. (Some
people may also argue that you're guaranteed that they
refer to a legitimate object, I don't buy this though...)

The advantage that pointers have over references are:

a) They can be reseated. One minute they can point East,
the next South West.

b) They can be incremented/decremented. If you have a
pointer to a character, you simply increment it and it
points to the next character in the string.

So...

Use references. If you can't, eg. you need to increment it
or seseat it, then *resort* to pointers.
-JKop
Jul 22 '05 #6
bo wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA


"Use references when you can, use pointers when you must" is my mantra.

Under the hood, both references and pointers are implemented using
pointers. Semantically however, references are "bound" to specific
variables, and do not "point" to arbitrary variables. That probably sums
up the difference between the two entities.

Using references makes my code cleaner and less error-prone because I
cannot manipulate a reference in such away that it "points" away from
the intended variable.

Using references also allows me to change a pass-by-value parameter to a
pass-by-reference without modifying the calling code. Consider these
function prototypes:

void Function_A(const Large_Class in);
void Function_B(const Large_Class& in);

These two functions are called in exactly the same way--Function_A(obj),
Function_B(obj). But the resulting calls are quite different. References
allow me to change the parameter-passing method as I develop my code
with minimal impact.
Jul 22 '05 #7
On Thu, 16 Sep 2004 07:32:44 -0500, bo <bo@cephus.com> wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...


Pointers are not suitable for operator overloading. Use
references in that case.

You cannot use references in standard containers. E.g. you must
write vector<X*> instead of vector<X&>. Use pointers in that
case.

References are guaranteed to refer to something. They cannot be
null. Use references unless you need the null value.

A reference cannot be reseated to another object. Use references
unless you need pointer arithmetic.

If a function modifies its argument, some programmers feel that
pointers are better because it makes it obvious that the arg can
be changed: f(&i)
Other programmers use a reference but choose a self-explicit
function name: modify(i)

Can't think of anything else right now...

Check
http://www.research.att.com/~bs/bs_f...and-references
And also, of course, section 8 of this newsgoup's FAQ.

--
Andre Heinen
My address, rot13-encoded: n qbg urvara ng rhebcrnayvax qbg pbz
Jul 22 '05 #8
Added to what everyone else has said, it is also important to understand the
implication of ownership when deciding whether to use a reference or a
pointer.

Pointer are generally used to take ownership ( responsible for deleting it
if it was new'd ) of an object, whereas a reference would be use when
someone else has ownership of the object.

While you could implement the "ownership/non-ownership" using a pointer in
both cases, it does make the code self documenting, and lets the compiler
check for bugs :-)

HTH
-Steve

"bo" <bo@cephus.com> wrote in message
news:9q********************************@4ax.com...
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA

Jul 22 '05 #9
* Ioannis Vranos:
Sharad Kala wrote:
http://www.parashift.com/c++-faq-lit...s.html#faq-8.6


I do not find that FAQ particularly useful. More accurately I believe it
is full of (nicely termed) nonsense.

Do you consider it useful?


The FAQ explained:
<q>Use references when you can, and pointers when you have to.</q>

Explanation: if you can use a reference, use a reference.

Otherwise, use a pointer.

This is good advice because references are more limited than pointers, so to
screw up you have to work much harder at it when all you have is a reference.

<q>References are usually preferred over pointers whenever you don't need
"reseating"</q>

Explanation: if you don't need to let the same variable refer to different
objects at different times, you can probably use a reference, and so you
should probably use a reference.
<q>This usually means that references are most useful in a class's public
interface.</q>

Explanation: the public interface of a class let's you pass information into
and get information out of an object. Unless there is a need for a logical
null-value this can be done using references. Hence use references here.
<q>References typically appear on the skin of an object, and pointers on the
inside.</q>

Explanation: in the code that implements an object pointers may be needed
because there one may need to let the same variable refer to different objects
at different times, or handle logical null-values. For example, in a linked
list class you need pointers inside. But the interface can be and probably
should be expressed with references only, giving the client code existence
guarantees that greatly simplifies the client code.
<q>The exception to the above is where a function's parameter or return value
needs a "sentinel" reference.</q>

Explanation: this is the logical null-value referred to above.
<q>This is usually best done by returning/taking a pointer, and giving the
NULL pointer this special significance (references should always alias
objects, not a dereferenced NULL pointer).</q>

Explanation: here Marshall Cline is expressing an opinion, which e.g. Bertrand
Meyer (the Eiffel man) seems to be diametrically opposed on. I'm personally
somewhere in between, choosing whatever seems most practical. But I think I
mostly lean in the direction Marshall is pointing here: it's too cumbersome to
have isVoid() functions, especially since a functional interface isn't
something that usually can be passed further around as data, as a pointer can.
<q>Note: Old line C programmers sometimes don't like references since they
provide reference semantics that isn't explicit in the caller's code.</q>

Explanation: people often do things out of habit and then rationalize it by
inventing reasons. Flame wars have therefore been fought over whether an "&"
in the client code indicates -- or not -- that an actual argument is an
out or an in/out (as opposed to pure in) argument. The facts are (1) that "&"
in the client code tells you nothing, (2) that in the C language the lack of
"&" tells you that argument is pure in, and (3) that in C++ the lack of "&"
doesn't tell you anything, either: you need to know about the function called.
<q>After some C++ experience, however, one quickly realizes this is a form of
information hiding, which is an asset rather than a liability.</q>

Explanation: this is not a technical comment but a methodological one. I
happen to agree with Marshall here but it's not universally agreed on. Anyway
the only connection to C++ is that the "&"-issue is a concrete example.
<q>E.g., programmers should write code in the language of the problem rather
than the language of the machine.</q>

Explanation: same as the previous one.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #10

"bo" <bo@cephus.com> skrev i en meddelelse
news:9q********************************@4ax.com...
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA


Have you read the faq pointed to by others? I believe it is quite good. No
specific implementation is required in the standard. That said, you can be
quite sure that a reference in the general case will be represented by a
pointervalue. In special cases, the value of the reference will be known and
no pointer will be stored.

/Peter
Jul 22 '05 #11
the main usefulness in my mind is maintainability; once you create a
reference variable you *know* it is always going to point to the same
thing, and that it is going to be non-null. But if you are reading code
with pointers in it you may not be sure that the author isn't going to
go changing the meaning later down in the code, and if he does you may
not be able to tell immediately whether it was intended or a bug.
Internally however, compilers I have seen have typically implemented
reference variables the same way they did pointers in terms of low-level
behavior.

Personally I spend a *lot* more time maintaining and reusing than I do
cutting new code, so any help I can get in terms of cues as to the
intended purpose and/or limitations of things are really helpful.

David

bo wrote:
And why and where one should use one vs. the other?

Verbally, it seems like semantics to me--but obviously there is some
actual difference that makes references different and or preferable
over pointers in some cases...

TIA

Jul 22 '05 #12
bo
Thanks to all who replied and the pointer (reference?) to the FAQ on
the subject! I am enlightened.....

Regards,

Bo

Jul 22 '05 #13
On Thursday 16 September 2004 06:12 am, JKop did deign to grace us with the
following:
bo posted:
And why and where one should use one vs. the other?
.... References are nicer to work with, in that they behave
exactly like real variables. a) They can be reseated. One minute they can point East,
the next South West.
This is probably just style, but this is why Pointers Are
Bad(TM). ;-)
b) They can be incremented/decremented. If you have a
pointer to a character, you simply increment it and it
points to the next character in the string.
I wouldn't even do this. If I really had to reference
string chars, I'd probably use *(ptr + i) and so on (i.e.,
not change the pointer itself if I didn't have to.) but
I guess we've already covered that, haven't we? (i.e. then
use a reference.) :-)
So...

Use references. If you can't, eg. you need to increment it
or seseat it, then *resort* to pointers.


Yeah - I cut my teeth on C with K&R at my elbow, and a tutor
who was about as smart as me - I wrote in a lot of printfs. ;-)
and have done a little thinking about pointers vs. references,
and I can't think of a single thing I'd want to do in real C++
that would need a pointer at all. I'm not porting any legacy
code - I intend to lift all new snippets to paste. ;-)
(I can pass for a programmer, but mostly what I do is copy
and paste other people's code. :-)

Cheers!
Rich

Jul 22 '05 #14
In message <btT2d.1520$Co1.271@trnddc02>, Rich Grise <nu**@example.net>
writes
On Thursday 16 September 2004 06:12 am, JKop did deign to grace us with the
following:
[...]
b) They can be incremented/decremented. If you have a
pointer to a character, you simply increment it and it
points to the next character in the string.


I wouldn't even do this. If I really had to reference
string chars, I'd probably use *(ptr + i) and so on (i.e.,
not change the pointer itself if I didn't have to.)


Pointers Are Iterators, so there's no harm in using the natural iterator
operations with them.
but
I guess we've already covered that, haven't we? (i.e. then
use a reference.) :-)
So...

Use references. If you can't, eg. you need to increment it
or seseat it, then *resort* to pointers.
Yeah - I cut my teeth on C with K&R at my elbow, and a tutor
who was about as smart as me - I wrote in a lot of printfs. ;-)
and have done a little thinking about pointers vs. references,
and I can't think of a single thing I'd want to do in real C++
that would need a pointer at all.


See above.
I'm not porting any legacy
code - I intend to lift all new snippets to paste. ;-)
(I can pass for a programmer, but mostly what I do is copy
and paste other people's code. :-)


--
Richard Herring
Jul 22 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

71
by: ROSY | last post by:
1. How would you use the functions memcpy(), memset(), memmove()?
9
by: Ching-Lung | last post by:
Hi all, I try to create a tool to check the delta (diff) of 2 binaries and create the delta binary. I use binary formatter (serialization) to create the delta binary. It works fine but the...
14
by: Robin Tucker | last post by:
Although I've been working on this project for 8 months now, I'm still not sure of the difference between ByVal and ByRef. As most objects in VB are reference types, passing ByVal I've discovered...
18
by: man | last post by:
can any one please tell me what is the diff between pointer and reference.....and which one is better to use ....and why???????
17
by: Rob Hoelz | last post by:
I've been compiling a list of the differences between C and C++, and I'd like to see how thorough I've been. Could any of you go over this list and see if I've missed anything? Here's the list:...
7
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
4
by: panks | last post by:
What is diff between Class c=new Class(); //Create object and Class c; c=new Class(); //create reference variable
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.