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

Stack Unwinding ใน C++

บทนำ

Stack Unwinding คือกระบวนการที่ function call stack entries ถูกลบออกในขณะรันไทม์ (runtime) เมื่อเราเรียกฟังก์ชัน มันเก็บที่อยู่ใน call stack และหลังกลับมาจากฟังก์ชัน จะ pop ที่อยู่ออกเพื่อทำงานต่อจากที่หยุดไว้

ถ้าเกิด exception ถูกโยนจากฟังก์ชันภายใน ทุก entry ใน stack จะถูกลบ และกลับไปที่ฟังก์ชันเรียกหลัก (main invoker)

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

void function1() throw (int) {
    cout << "\n Entering into function 1";
    throw 100;
    cout << "\n Exiting function 1";
}

void function2() throw (int) {
    cout << "\n Entering into function 2";
    function1();
    cout << "\n Exiting function 2";
}

void function3() {
    cout << "\n Entering function 3 ";
    try {
        function2();
    } catch(int i) {
        cout << "\n Caught Exception: " << i;
    }
    cout << "\n Exiting function 3";
}

int main() {
    function3();
    return 0;
}

ผลลัพธ์

Entering function 3
Entering into function 2
Entering into function 1
Caught Exception: 100
Exiting function 3

เห็นได้ว่า control เก็บข้อมูล function3 แล้วเข้า function2 แล้ว function1 เกิด exception จึงลบข้อมูลทั้งหมดจาก stack และกลับไปที่ function3 อีกครั้ง