• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c++whydoesn'tc++allowrebindingareference?

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C语言变量和常量发布时间:2022-07-14
下一篇:
数组名与函数指针(C++)发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap