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

Copy-and-swap Idiom ใน C++ คืออะไร


Copy-and-swap = เทคนิค implement assignment operator (operator=) ที่ปลอดภัยและ exception-safe

Assignment มี 2 ขั้นตอน: (1) ทำลายสถานะเก่า (destructor) (2) สร้างสถานะใหม่ (copy constructor) การ overload operator= ตรงๆ ยากที่จะทำให้ exception-safe

หลักการ Copy-and-swap

  1. ใช้ copy constructor สร้าง local copy ของข้อมูลใหม่ (ถ้า throw exception object ต้นฉบับไม่เสียหาย)
  2. Swap ข้อมูลเก่ากับข้อมูลใหม่ (swap function - nothrow)
  3. Local copy (เก่าของข้อมูล) ถูก destroy อัตโนมัติเมื่อออก scope (destructor)

ต้องมี 3 อย่าง:

  • Copy constructor
  • Destructor
  • Swap function (no-throw, swap members ทีละตัว อย่าใช้ std::swap เพราะมันใช้ copy/assign เอง)

ผลลัพธ์: ได้ exception-safe assignment operator แบบ strong guarantee