In C , the placement of the const reference in function arguments can raise questions. Consider the following two code snippets:
int foo1(const Fred &arg) { ... }
int foo2(Fred const &arg) { ... }
Semantically, there is no difference between these two arguments. The language treats them as the same type, both referring to a constant reference to an object of type Fred.
Stylistic Considerations:
However, when it comes to style, the preferred usage varies among programmers.
Right-to-Left Parsing:
According to the right-to-left parsing rule, qualifiers (such as const) should be applied to the type on their left. This would support the use of T const&.
However, it's important to note that const T& can also be parsed effectively right-to-left. It indicates a reference to a constant value of type T. Furthermore, the ambiguity of T const* (which could potentially be interpreted as "pointer constant to T" instead of "pointer to constant T") makes const T& the more unambiguous choice.
Practicality:
In terms of readability and common usage, const T&/const T have gained significant momentum over T const&/T const. This may be due to the prevalence of these styles in widely recognized sources like Stroustrup's book and the C standard. Adhering to commonly accepted practices can enhance code readability.
The above is the detailed content of Const References in Function Arguments: `const T&` or `T const&`?. For more information, please follow other related articles on the PHP Chinese website!