tags:

views:

218

answers:

2

I've read many discussions on the difference between references and pointers and when to use which. They all seem to get their conclusions from analysis of the behaviors of the two.

But I'd still like to know what was in the language designers' mind. What's the main motive for this design? In what typical situation is it intended to be used? Perhaps the answer is already included in the discussions I mentioned, but I want to know which are authentic.

P.S. Does reference have a history as long as pointer in C++? Was it originated from the very beginning or came up as a patch for some situations? Thanks a lot.

+3  A: 

From the FAQ:

Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.

Along with this article it should answer some of your questions (most likely except for the history). You can always dig into the standard, but I find it unlikely that there will be any nice tale about the origin of references...

Anonymous
I've read the Wikipedia article, and found no clue.
A reference is a pointer. It's quite important to understand that when debugging memory problems etc etc.
Marcus Lindblom
A reference is NOT a pointer, but sometimes is implemented with a pointer behind the scenes. Sometimes it's not, in which case the previous advice will be a major red herring. In particular, temporaries bound to a reference (i.e. `T const`) are unlikely to be implemented as a pointer.
MSalters
A reference is a pointer that is guaranteed by the compiler not to be null.
Dimitri C.
A reference is NOT a pointer. It IS an ALIAS. Thinking of it as a pointer will get you into trouble while debugging. When the code is compiler there may potentially be no pointers anywhere if the optimizer is doing its job. Note: taking the address of a pointer and taking the address of a reference will give you very different things.
Martin York
+15  A: 

Here's Stroustrup's reasons for adding them to the language.

Basically they were mainly added to support operator overloading.

Glen
Wow, this is really a direct answer. Thank you.