Copy-and-swap = เทคนิค implement assignment operator (operator=) ที่ปลอดภัยและ exception-safe
Assignment มี 2 ขั้นตอน: (1) ทำลายสถานะเก่า (destructor) (2) สร้างสถานะใหม่ (copy constructor) การ overload operator= ตรงๆ ยากที่จะทำให้ exception-safe
หลักการ Copy-and-swap
- ใช้ copy constructor สร้าง local copy ของข้อมูลใหม่ (ถ้า throw exception object ต้นฉบับไม่เสียหาย)
- Swap ข้อมูลเก่ากับข้อมูลใหม่ (swap function - nothrow)
- 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