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

วิธีเข้าถึง local variable จากฟังก์ชันอื่นด้วย pointers ใน C++


ปกติแล้วทำไม่ได้: local variable หายไปเมื่อออก scope (ฟังก์ชันจบ) การเข้าถึงผ่าน pointer ที่ชี้ไปที่ memory ที่ free แล้ว = Undefined Behavior

ตัวอย่างที่อาจทำงาน (แต่ไม่ควรทำ)

#include <iostream>
int* foo() {
    int x = 3;
    return &x;  // คืน address ของ local variable!
}
int main() {
    int* address = foo();
    cout << *address;  // อาจพิมพ์ 3
    *address = 12;     // เขียนทับ memory ที่ freed แล้ว
    cout << *address;  // อาจพิมพ์ 12
}

ผลลัพธ์ที่อาจได้

3 12

ทำไมบางครั้งทำงานได้: memory ของ x ยังไม่ถูก reuse/overwrite OS ยังไม่ reclaim แต่เป็น เรื่องโชคดี (luck) ไม่ได้รับประกัน

ในโปรแกรมจริง: memory นั้นจะถูก reuse ทันที การเขียน/อ่านจะทำลายข้อมูลอื่น หรือ crash ได้ยากต่อการ debug

วิธีแก้: ส่งค่ากลับ (return by value), ใช้ reference parameter, dynamic allocation (new/smart pointer), หรือ static/storage duration