Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Reference Parameters ใน C++: Call by Reference และการสลับค่า

Reference Parameter (Call by Reference) ใน C++ ช่วยให้ฟังก์ชันเข้าถึงและแก้ไข Argument ต้นฉบับได้โดยตรง แทนที่จะทำงานบน Copy (Call by Value) ใช้สัญลักษณ์ & ติดกับ Parameter Type

Syntax และกลไก


// Declaration
void swap(int& x, int& y); // x, y เป็น Reference ไปยัง Argument จริง

// Definition
void swap(int& x, int& y) {
    int temp = x;
    x = y;      // แก้ไข Argument ต้นฉบับ
    y = temp;   // แก้ไข Argument ต้นฉบับ
}

ตัวอย่างสมบูรณ์: Swap Function

#include <iostream>

void swap(int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 100;
    int b = 200;
    
    std::cout << "Before swap: a = " << a << ", b = " << b << '\n';
    swap(a, b); // ส่ง Reference ของ a, b
    std::cout << "After swap:  a = " << a << ", b = " << b << '\n';
    
    // Output:
    // Before swap: a = 100, b = 200
    // After swap:  a = 200, b = 100
}

Call by Value vs Call by Reference

ด้านCall by ValueCall by Reference
Syntaxvoid f(int x)void f(int& x)
MechanismCopy ArgumentBind Reference to Argument
Modify Original?❌ ไม่ได้✅ ได้
Performance (Large Objects)Copy Cost สูงCheap (Pointer-like)
Const Correctnessไม่เกี่ยวใช้ const T& สำหรับ Read-Only

Const Reference: สำหรับ Read-Only Large Objects


// Good: หลีกเลี่ยง Copy String/Vector ขนาดใหญ่
void print(const std::string& s) { 
    std::cout << s << '\n'; 
}

// Bad: Copy ทุกครั้ง
void print_bad(std::string s) { 
    std::cout << s << '\n'; 
}

Rvalue Reference (C++11): Move Semantics


void process(std::string&& s) { // Rvalue Reference
    // สามารถ Move จาก s ได้
    store(std::move(s));
}

process("temporary"); // OK: String Literal -> Temporary -> Rvalue
std::string str = "hello";
process(std::move(str)); // OK: Explicit Move

ข้อระวัง

  • Dangling Reference: คืน Reference ของ Local Variable → Undefined Behavior
  • Reference to Temporary: const int& r = 5; OK (Lifetime Extended), แต่ int& r = 5; Error
  • Reference Parameter ไม่สามารถ Reseat ได้: ผูกติดกับ Argument ตัวเดียวตลอดชีวิต

สรุป

Reference Parameter (T&) เป็นกลไกพื้นฐานของ C++ สำหรับ Output Parameters, In/Out Parameters, และ Efficient Read-Only Access (const T&) เข้าใจความแตกต่างจาก Pointer และ Value Semantics จำเป็นสำหรับการเขียน C++ ที่ถูกต้องและมีประสิทธิภาพ