Const Reference Types in C++: Placement of the 'const' Qualifier
In C++, there are two ways to declare constant references using the 'const' qualifier:
const Fred &arg; Fred const &arg;
Semantic Differences
Semantically, these two declarations are equivalent, and the language considers them as the same type. There is no functional difference between passing an argument by const T& or T const&.
Style Considerations
However, when it comes to style, there are different preferences among programmers.
Left-to-Right Parsing
Some programmers advocate for placing the 'const' qualifier after the type (T const&), arguing that it follows the right-to-left parsing rule in C++. This ensures that when reading the declaration, the 'const' qualifier is applied to the type, rather than to the reference itself.
Right-to-Left Parsing
Others, however, prefer the const T& syntax, arguing that it reads equally well right-to-left. It can be interpreted as "reference to a T constant". Furthermore, placing the 'const' qualifier before the reference prevents the accidental declaration of a pointer constant, such as 'T* const' which is illegal.
Common Practice
In practice, both styles are widely used. The style preferred by Stroustrup's "The C++ Programming Language" and the C++ standard is const T&. However, the style used in K&R's "The C Programming Language" and the C standard is T const*. Ultimately, the choice of style is a matter of personal preference and may also be influenced by the coding conventions of specific organizations.
Atas ialah kandungan terperinci Rujukan Const dalam C : `const T&` atau `T const&` – Apakah Perbezaannya?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!