c++ why doesn't c++ allow rebinding a reference ?

1. The primary reason that the designer of C++ introduced reference into the language is to support "encapsulated" address passing (to or from a function).

C++ Primer 4th Edition Section 2.5:

In real-world programs, references are primarily used as formal parameters to functions.

If you're planning to return a reference from a function, you must be sure it's "safe" to do so. See C++ Primer 4th Edition Section 7.3.2 Subsection "Returning a Reference"

2. Another reason is the syntax. In Java, assignning to a reference always means "rebind this reference so it points to another object" (which is exactly the same meaning as you assign to a pointer in C++), note that in Java, primitive types don't have references, however in C++, primitive types can also have references, and assigning to a reference of a primitive type means "assign the value of the object on the right side of the = operator to the object pointed by the reference on the left side of the = operator", this meaning also applies on class-type objects. When you're aware of this fact, it's easy to see that if you want to "rebind" a reference to another object, you'll have to invent a new operator (if you still use the operator "=", how would the compiler know whether you're assigning value or rebinding a reference?) to stand for the "rebind" operation, which is unnecessary because you can just use pointers instead.

 

In short.

1. Reference is just designed to support glorified "address passing", primarily used as parameters and/or return values. Not to replace pointers.

2. Because pointers can "rebind", so we don't need the same thing twice.

posted @ 2014-11-20 18:39  rldts  阅读(440)  评论(0编辑  收藏  举报