Pointer Arithmetic
เพิ่ม typed pointer หนึ่งครั้งจะเลื่อนไปหนึ่ง element ไม่ใช่หนึ่ง byte
Pointer Arithmetic คืออะไร?
เพิ่ม typed pointer หนึ่งครั้งจะเลื่อนไปหนึ่ง element ไม่ใช่หนึ่ง byte
วนหน่วยความจำต่อเนื่องด้วย pointer และ iterator
ประเด็นสำคัญ
- Pointer ต้องชี้ object ที่ยังมีชีวิตและ type ตรงกันหรือเป็น null
- Allocation ที่เป็นเจ้าของต้องถูก free เพียงครั้งเดียว
- ระบุ ownership และ const ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
int values[] = {10, 20, 30, 40};
int sum = 0;
for (int *p = values; p < values + 4; ++p) sum += *p;
printf("sum=%d distance=%td\n", sum, (values + 4) - values);
return 0;
}
sum=100 distance=4
C++
main.cpp
#include <iostream>
#include <vector>
int main() {
std::vector values{10, 20, 30, 40};
int sum = 0;
for (auto it = values.begin(); it != values.end(); ++it) sum += *it;
std::cout << "sum=" << sum << " distance="
<< std::distance(values.begin(), values.end()) << '\n';
}
sum=100 distance=4
เปรียบเทียบ C และ C++
ใช้ได้เฉพาะใน array เดียวจนถึง one-past-end ส่วน iterator C++ ขยายแนวคิดไปยัง container
C
Ownership และ cleanup เป็นกฎที่โปรแกรมเมอร์ต้องดูแล
C++
Container และ RAII ผูก ownership กับ lifetime ของ object
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- ทดสอบ null และ allocation failure
- ใช้ AddressSanitizer และ UndefinedBehaviorSanitizer
- บันทึก ownership ของ pointer ทุกตัว