问题描述
如果 const关键字所引用的对象不是const对象,该关键字的用途是什么? r1和r2(下)之间有什么区别?
What is the purpose for the "const" keyword for a reference if the object it is referencing is not a const object? Is there any difference between what r1 and r2 does (below)?
int i = 42; // non const object
const int &r1 = i; // const reference to non const object
int j = 25; // non const object
int &r2 = j; // non const reference to non const object
以下是CPP Primer 5th的引文:
Here's a quote from CPP Primer 5th:
C ++程序员倾向于将短语引用const缩写为
常量引用。这个缩写是有道理的-如果您还记得
是缩写,则
从技术上讲,没有const引用。引用不是
对象,因此我们不能将引用本身设为const。确实,因为没有
的引用可以引用另一个对象,所以从某种意义上说,所有
引用都是const。引用是引用const还是非const
类型都会影响我们可以使用该引用,而不是是否可以更改
引用本身的绑定。
"C++ programmers tend to abbreviate the phrase "reference to const" as"const reference." This abbreviation makes sense—if you remember that itis an abbreviation.Technically speaking, there are no const references. A reference is not anobject, so we cannot make a reference itself const. Indeed, because thereis no way to make a reference refer to a different object, in some sense allreferences are const. Whether a reference refers to a const or nonconsttype affects what we can do with that reference, not whether we can alterthe binding of the reference itself."
我认为这意味着将引用设为常量当引用到非const对象时,绝对不会执行任何操作。在定义该引用时,我们也可以删除const关键字。
I think this means that making a reference a "const" when it is referenced to a non const object does absolutely nothing. We may as well take that const keyword out when defining that reference.
在此处提出问题以进行确认。
Asking this question here for confirmation.
编辑:看来我最初的猜想是错误的。我现在了解,对非const对象的const引用确实有一个目的:防止引用修改该对象。仍然可以通过其他方式修改非const对象,但不能通过此const引用对其进行修改。
Looks like my initial conjecture is wrong. I understand now that a const reference to a non const object does have a purpose: to prevent the reference from modifying the object. The non const object can still be modified by other means but not by this const reference.
谢谢。
推荐答案
如果所引用的对象不是const对象, const关键字用于引用的目的是什么?
目的是防止该引用用于修改其引用的对象。
"What is the purpose for the "const" keyword for a reference if the object it is referencing is not a const object?"The purpose is to prevent that reference being used to modify the object it is referencing.
int i = 42; // non const object
const int &r1 = i; // const reference to non const object
r1 = 6 * 9; // error, r1 cannot be used to modify i;
这篇关于常量引用非常量对象和常量引用非常量对象之间的C ++区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!