ใน C++ หน่วยความจำหลักแบ่งเป็น 2 ส่วนสำคัญสำหรับ object:
- Stack – ตัวแปร/อ็อบเจ็กต์ที่ประกาศภายใน block (function, loop, if, scope) จะจัดเก็บที่นี่ ทำลายอัตโนมัติเมื่อออกจาก scope
- Heap – object ที่สร้างด้วย
new(dynamic allocation) จะอยู่ที่นี่ ต้องdeleteเอง
ตัวอย่างแสดงพฤติกรรม
#include <iostream>
using namespace std;
class Box {
int width, length;
public:
Box(int l = 0, int w = 0) : length(l), width(w) {}
~Box() { cout << "Box is destroying" << endl; }
int get_len() { return length; }
int get_width() { return width; }
};
int main() {
{ // Block ใหม่
Box b(2, 3); // Stack allocation
cout << "Box dimension: " << endl;
cout << "Length: " << b.get_len() << endl;
cout << "Width: " << b.get_width() << endl;
} // b ถูกทำลายที่นี่ (destructor เรียก)
cout << "\tExiting block, destructor auto-called for stack object." << endl;
Box* box_ptr;
{ // Block อีกอัน
Box* box_ptr1 = new Box(5, 6); // Heap allocation
box_ptr = box_ptr1;
cout << "Box 2 dimension: " << endl;
cout << "Length: " << box_ptr1->get_len() << endl;
cout << "Width: " << box_ptr1->get_width() << endl;
delete box_ptr1; // ต้อง delete เอง
}
// box_ptr ยังชี้ไปที่ memory เดิม แต่ object ถูกลบแล้ว (dangling pointer)
cout << "Length of box2: " << box_ptr->get_len() << endl; // Undefined behavior!
cout << "Width of box2: " << box_ptr->get_width() << endl;
}
เอาต์พุท
Box dimension is:
Length: 2
Width: 3
Box is destroying
Exiting block, destructor automatically called for stack object.
---------------------------------------------------
Box 2 dimension is:
Length: 5
Width: 6
Box is destroying
Length of box2: 0
Width of box2: 0
สรุป
| ลักษณะ | Stack | Heap |
|---|---|---|
| การจัดสรร | อัตโนมัติ (ประกาศตัวแปร) | manual (new) |
| อายุการใช้งาน | ผูกกับ scope | จนกว่าจะ delete |
| ความเร็ว | เร็วมาก | ช้ากว่า |
| ขนาด | จำกัด (ประมาณ 1-8 MB) | ใหญ่ (ขึ้นกับ RAM) |
| การจัดการหน่วยความจำ | อัตโนมัติ | manual (ต้อง delete) |