const correctness
const บอกว่า object ใดไม่ถูกแก้และให้ compiler ป้องกัน write ที่ผิด
const correctness คืออะไร?
const บอกว่า object ใดไม่ถูกแก้และให้ compiler ป้องกัน write ที่ผิด
ระบุข้อมูล read-only และ pointer ที่เปลี่ยนได้อย่างแม่นยำ
ประเด็นสำคัญ
- Pointer ต้องชี้ object ที่ยังมีชีวิตและ type ตรงกันหรือเป็น null
- Allocation ที่เป็นเจ้าของต้องถูก free เพียงครั้งเดียว
- ระบุ ownership และ const ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int sum(const int *values, size_t count) {
int total = 0;
for (size_t i = 0; i < count; ++i) total += values[i];
return total;
}
int main(void) {
const int values[] = {2, 4, 6};
printf("%d\n", sum(values, 3));
return 0;
}
12
C++
main.cpp
#include <array>
#include <iostream>
int sum(const std::array<int, 3>& values) {
int total = 0;
for (int value : values) total += value;
return total;
}
int main() {
const std::array values{2, 4, 6};
std::cout << sum(values) << '\n';
}
12
เปรียบเทียบ C และ C++
Pointer-to-const ป้องกัน value ส่วน const pointer เปลี่ยน address ไม่ได้ C++ มี const member function เพิ่ม
C
Ownership และ cleanup เป็นกฎที่โปรแกรมเมอร์ต้องดูแล
C++
Container และ RAII ผูก ownership กับ lifetime ของ object
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- ทดสอบ null และ allocation failure
- ใช้ AddressSanitizer และ UndefinedBehaviorSanitizer
- บันทึก ownership ของ pointer ทุกตัว