หัวใจสำคัญ
ใน C/C++ เมื่อ Assign Struct/Class Variable ให้กับอีกตัวหนึ่งประเภทเดียวกัน Array Members จะถูก Deep Copy อัตโนมัติ โดย Compiler (ไม่ใช่ Shallow Copy)
ตัวอย่างยืนยัน
#include <iostream>
#include <cstring>
using namespace std;
struct Test {
char str[20];
};
int main() {
Test st1, st2;
strcpy(st1.str, "Tutorial Point");
st2 = st1; // Assignment - Compiler ทำ Deep Copy Array
st1.str[0] = 'X'; // แก้ไข st1
st1.str[1] = 'Y';
cout << "st1's str = " << st1.str << endl; // XYtorial Point
cout << "st2's str = " << st2.str << endl; // Tutorial Point (ไม่เปลี่ยน!)
return 0;
}
ผลลัพธ์
st1's str = XYtorial Point
st2's str = Tutorial Point
คำอธิบาย
st2 = st1ทำให้ ทุก Byte ของ Array ถูก Copy ไปยังst2.strst1.strและst2.strเป็น Array แยกกันสมบูรณ์ (Different Memory Locations)- การแก้ไขหนึ่งไม่ส่งผลต่ออีกตัว
เปรียบเทียบกับ Pointer Members
| Member Type | Default Copy Behavior | ต้องเขียน Copy Constructor? |
|---|---|---|
| Array (Fixed Size) | Deep Copy ✓ | ไม่จำเป็น |
| Pointer | Shallow Copy (Copy Address) | จำเป็น (ถ้าต้องการ Deep Copy) |
| std::vector, std::string | Deep Copy (มี Copy Constructor ของตัวเอง) | ไม่จำเป็น |
| Primitive Types (int, float, etc.) | Value Copy | ไม่จำเป็น |