为什么引用在C ++中不可重用 [英] Why are references not reseatable in C++

查看:185
本文介绍了为什么引用在C ++中不可重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++引用有两个属性:




  • 它们总是指向同一个对象。

  • 它们不能为0。



指针是相反的:






$ b p>为什么在C ++中没有非可空,可重复的引用或指针?我不能想到引用不可重复的好理由。



编辑:
这个问题经常出现因为我通常使用引用,当我想确保一个关联(我在这里避免单词引用或指针)从不无效。



我不认为我曾经认为伟大的,这ref总是指同一个对象。如果引用是可重用的,那么仍然可以得到如下的当前行为:

  int i = 3; 
int&const j = i;

这已经是合法的C ++,但是没有意义。



我这样重申我的问题:引用背后的理由是对象的设计?



Cheers,Felix

$ b有用的是引用总是 $ b

解决方案

在C ++中,经常说引用是对象。在某种意义上,它是真的:虽然引用被处理为指针,当源代码编译时,引用旨在表示一个对象,当一个函数被调用时不被复制。因为引用不是直接可寻址的(例如,引用没有地址,并返回对象的地址),所以重新赋值它们在语义上没有意义。此外,C ++已经有指针,它处理重新设置的语义。


C++ references have two properties:

  • They always point to the same object.
  • They can not be 0.

Pointers are the opposite:

  • They can point to different objects.
  • They can be 0.

Why is there no "non-nullable, reseatable reference or pointer" in C++? I can't think of a good reason why references shouldn't be reseatable.

Edit: The question comes up often because I usually use references when I want to make sure that an "association" (I'm avoiding the words "reference" or "pointer" here) is never invalid.

I don't think I ever thought "great that this ref always refers to the same object". If references were reseatable, one could still get the current behavior like this:

int i = 3;
int& const j = i;

This is already legal C++, but meaningless.

I restate my question like this: "What was the rationale behind the 'a reference is the object' design? Why was it considered useful to have references always be the same object, instead of only when declared as const?"

Cheers, Felix

解决方案

In C++, it is often said that "the reference is the object". In one sense, it is true: though references are handled as pointers when the source code is compiled, the reference is intended to signify an object that is not copied when a function is called. Since references are not directly addressable (for example, references have no address, & returns the address of the object), it would not semantically make sense to reassign them. Moreover, C++ already has pointers, which handles the semantics of re-setting.

这篇关于为什么引用在C ++中不可重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆