1.
中文版:
设置一个类型为auto的引用时,初始值中的顶层常量属性依然保留。和往常一样,如果我们给初始值绑定一个引用,则此时的常量就不是顶层常量了。”
英文版:
When we ask for a reference to an auto-deduced type, top-level consts in the initializer are not ignored. As usual, consts are not top-level when we bind a reference to an initializer
怎么理解这段话呢?能否举例说明?
top-level
const
:const
modifies itself.low-level
const
:const
modifies someone else .What is oneself and what is others? In the world of C++:
So, there are the following rules:
The- pointer can be top-level
- References can only be low-level
When is theconst
or low-levelconst
.const
.pointer top-level
const
and when is it low-levelconst
? Please refer to your other question answered yesterday.(
const char *
is low-level,char * const
is top-level.)If you understand the above concepts, let’s understand what you quoted. Example:
Okay,
ci
isconst int
, which is top-levelconst
; what aboutr1
? It'sconst int&
, it's a reference, and the reference must be low-levelconst
.So:
Do you agree with the second part?
Look at
r1
in the example. Can you modify it? You may be confused, nonsense, even after addingconst
, can it still be modified?Let’s look at another example:
See, for pointers, low-level
const
can be modified! (Corresponding to the concept of starting, the pointer can be "someone else", and someone else isconst
, which does not affect the pointer pointing to another person)Then
const int*
can be modified, butconst int&
cannot be modified, which is caused by the concept of reference itself (it cannot be bound again once initialized).That is, while the
const
reference is low-levelconst
, it also has the characteristics of top-levelconst
, that is, "itself" cannot be modified.So:
means "the top-level constant attributes are still retained". Let's understand the meaning of the top-level constant attributes mentioned here.
In summary, combine the examples I gave. The simplest explanation:
auto &r1 = ci;
What happened?const
to low-levelconst
.const
(which cannot be modified) are still retained.Is it clear?
PS: Why does C++ Primer advocate using more references and less pointers? Because pointers are too flexible. Quoting is easier to control. . .
There are many tutorials in this area, so I simply wrote them down. If you don’t understand them correctly, please feel free to correct me.