FAQ 11.10 Aren t references just pointers in disguise?

FAQ 11.10 Aren't references just pointers in disguise?

No, they are not.

It is important to realize that references and pointers are quite different. A pointer should be thought of as a separate object with its own distinct set of operations (*p, p->blah, and so on). So creating a pointer creates a new object. In contrast, creating a reference does not create a new object; it merely creates an alternative name for an existing object. Furthermore the operations and semantics for the reference are defined by the referent; references do not have operations of their own.

In the following example, notice that assigning 0 to the reference j is very different than assigning 0 to the pointer p (the 0 pointer is the same as the NULL pointer; see FAQ 1.09).

 int main() {   int  i = 5;   int& j = i;                                        <-- 1   int* p = &i;                                       <-- 2   j = 0;                                             <-- 3   p = 0;                                             <-- 4 } 

(1) j is an alias for i

(2) p is a new object, not an alias

(3) Changes i

(4) Changes p; does not affect i

Because of their low-level nature, pointers are poor substitutes for references. Holding on to the belief that pointers and references are the same is like saying that char* and a string class are the same or that void* and long are the same there is a way to map from one to the other but the mapping is forced and is unnatural. Furthermore, the purpose of programming in C++ is not to write C++ programs that look just like C programs.

Pointers and references are not the same, even though many compilers implement them using similar assembly language instructions. This is an implementation detail that does not change the message of this FAQ.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net