ประเด็นนี้เกี่ยวกับ Type Qualifiers และ Reference Semantics ใน C++
int (Plain Integer)
- Value Type: เก็บค่าตรงๆ
- Pass by Value: Copy ค่า
- Mutable: เปลี่ยนค่าได้
const int& (Reference to Const Int)
- Reference Type: อ้างอิงไปยัง
intObject ที่มีอยู่ - Pass by Reference: ไม่ Copy, เข้าถึง Object ต้นฉบับ
const: ไม่สามารถแก้ไขผ่าน Reference นี้ได้ (แต่ Object ต้นฉบับอาจ Mutable)- Bind ได้กับ: Lvalue, Rvalue, Const Object, Literal (Temporary Lifetime Extension)
ความสับสนทั่วไป: int& const vs const int&
int x = 10;
int& const ref1 = x; // Error: "const" บน Reference เอง (Top-level CV on Reference) ไม่ได้หมายอะไร
// Reference ไม่สามารถ Reseat ได้อยู่แล้ว (Always "const" ในความหมายนี้)
const int& ref2 = x; // OK: Reference to CONST int
int const& ref3 = x; // OK: เหมือนกัน (const int == int const)
กฎ: const ทางซ้ายสุด (หรือหลัง Type) Qualify Type (const int) const ทางขวาสุด Qualify Reference/Pointer เอง (int& const - Redundant/Illegal)
ตัวอย่างการใช้งาน
void func_value(int x) { x = 20; } // Copy, แก้ Copy ได้
void func_ref(int& x) { x = 20; } // Reference, แก้ Original ได้
void func_cref(const int& x) { /*x=20;*/ } // Const Ref, อ่านอย่างเดียว, Bind ทุกอย่างได้
int main() {
int a = 10;
const int b = 20;
func_value(a); // a ยังคง 10
func_ref(a); // a กลายเป็น 20
// func_ref(b); // Error: Cannot bind non-const ref to const
func_cref(a); // OK
func_cref(b); // OK
func_cref(30); // OK: Bind to Temporary (Lifetime Extended)
}
เมื่อไหร่ใช้ const int&?
- Function Parameter สำหรับ Read-Only Large Objects (หลีกเลี่ยง Copy)
- รองรับทั้ง Lvalue และ Rvalue (Temporary)
- Const Correctness: บอก Caller ว่า "ฟังก์ชันนี้ไม่แก้ Argument"
สรุป
int = Value, const int& = Reference to Const Int (Read-only View) int& const ไม่มีความหมาย (Reference ไม่สามารถ Reseat ได้แล้ว) ใช้ const T& สำหรับ Parameter ที่อ่านอย่างเดียวและใหญ่ (Strings, Vectors, User Types)