Rumah > pembangunan bahagian belakang > C++ > Rujukan Const dalam C : `const T&` atau `T const&` – Apakah Perbezaannya?

Rujukan Const dalam C : `const T&` atau `T const&` – Apakah Perbezaannya?

Barbara Streisand
Lepaskan: 2024-11-14 18:23:02
asal
590 orang telah melayarinya

Const Reference in C++: `const T&` or `T const&` – What's the Difference?

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;
Salin selepas log masuk

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!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan