所以,我意识到 const T&
和 T const&
是相同的,都表示对 const T 的引用.在这两种情况下,引用也是常量(与指针不同,不能重新分配引用).我观察到,以我有限的经验,大多数 C++ 程序员使用 const T&
,但我遇到过一些使用 T const&
的人.我使用 const T&
只是因为我是那样学的,所以 T const&
对我来说看起来有点好笑.您使用您使用的变体的原因是什么?你们中是否有人在编码标准要求使用一种变体而不是另一种变体的组织工作?
So, I realize that const T&
and T const&
are identical and both mean a reference to a const T. In both cases, the reference is also constant (references cannot be reassigned, unlike pointers). I've observed, in my somewhat limited experience, that most C++ programmers use const T&
, but I have come across a few people who use T const&
. I use const T&
simply because I learned it that way, and so T const&
looks a little bit funny to me. What is the reason that you use the variant that you use? Do any of you work at an organization for which the coding standards mandate the use of one variant over the other?
编辑
根据这些答案,在两者之间进行选择的一个原因似乎是您想像编译器(从右到左)还是像英语(从左到右)一样阅读它.如果像编译器一样读取它,那么T const&"读作& (reference) const (to a constant) T (of type T)".如果从左到右读起来像英语一样,那么const T&"读作引用形式的 T 类型常量对象".我更喜欢像读英文散文一样阅读它,但我当然可以看到以编译器的方式解释它的意义.
Edit
Based on the answers, it would appear that one reason for choosing between the two is whether you want to read it like the compiler (right-to-left) or like English (left-to-right). If one reads it like the compiler, then "T const&" reads as "& (reference) const (to a constant) T (of type T)". If one reads it like English, from left-to-right, then "const T&" is read as "a constant object of type T in the form of a reference". I prefer to read it like English prose, but I can certainly see the sense in interpreting it the way that the compiler does.
没有人回答组织或编码标准的问题,但我强烈怀疑大多数组织不会强制要求一个而不是另一个,尽管他们可能会努力保持一致性.
No one has answered the organization or coding standards question, but I strongly suspect that most organizations do not mandate one over the other, although they might strive for consistency.
我认为有些人只是喜欢从右到左阅读声明.const
适用于左边的标记,除非那里什么都没有,而且它适用于右边的标记.因此,const T&
包含except"子句,可能会被认为更复杂(实际上两者都应该很容易理解).
I think some people simply prefer to read the declarations from right to left. const
applies to the left-hand token, except when there is nothing there and it applies on the right-hand token. Hence const T&
involves the "except"-clause and can perhaps be thought more complicated (in reality both should be as easy to understand).
比较:
const T* p; (pointer to T that is const)
T const* p; (pointer to const T) //<- arguable more natural to read
T* const p; (const pointer to T)
这篇关于为什么有些人更喜欢“T const"?超过“const T"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!