Pointer และหน่วยความจำ

Function Pointer และ Callback

Callback ทำให้ algorithm เรียก behavior ที่ caller เลือก

Function Pointer และ Callback คืออะไร?

Callback ทำให้ algorithm เรียก behavior ที่ caller เลือก

ส่ง behavior ไปยังฟังก์ชันอื่น

ประเด็นสำคัญ

  • Pointer ต้องชี้ object ที่ยังมีชีวิตและ type ตรงกันหรือเป็น null
  • Allocation ที่เป็นเจ้าของต้องถูก free เพียงครั้งเดียว
  • ระบุ ownership และ const ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>

int square(int value) { return value * value; }
int apply(int value, int (*operation)(int)) { return operation(value); }

int main(void) {
    printf("%d\n", apply(6, square));
    return 0;
}
ผลลัพธ์ที่คาดหวัง
36
C++
รันโค้ด →
main.cpp
#include <functional>
#include <iostream>

int apply(int value, const std::function<int(int)>& operation) {
    return operation(value);
}

int main() {
    int factor = 6;
    std::cout << apply(factor, [](int value) { return value * value; }) << '\n';
}
ผลลัพธ์ที่คาดหวัง
36

เปรียบเทียบ C และ C++

C ใช้ type ของ function pointer ชัดเจน ส่วน C++ ใช้ lambda และ std::function ที่มี state ได้

C

Ownership และ cleanup เป็นกฎที่โปรแกรมเมอร์ต้องดูแล

C++

Container และ RAII ผูก ownership กับ lifetime ของ object

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • ทดสอบ null และ allocation failure
  • ใช้ AddressSanitizer และ UndefinedBehaviorSanitizer
  • บันทึก ownership ของ pointer ทุกตัว