为什么有些人更喜欢"T const&"?超过"const T&"? [英] Why do some people prefer "T const&" over "const T&"?

查看:100
本文介绍了为什么有些人更喜欢"T const&"?超过"const T&"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我意识到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&"读取为(类型为T的)&(引用)const(表示常量)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&amp;"?超过"const T&amp;"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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