在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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:
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. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论