const correctness
constは変更しない契約を示し、誤ったwriteをcompilerが拒否します。
const correctnessとは?
constは変更しない契約を示し、誤ったwriteをcompilerが拒否します。
読み取り専用データと変更可能なpointerを正確に表します。
重要なポイント
- ポインタは生存中の互換オブジェクトを指すかnullである必要があります。
- 所有するallocationは一度だけ解放します。
- ownershipとconstを明確に表現します。
Cと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は値を、const pointerは指し先を固定します。C++にはconst member functionもあります。
C
ownershipとcleanupはプログラマが守る規約です。
C++
containerとRAIIがownershipとcleanupをlifetimeに結び付けます。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- nullとallocation失敗をテストします。
- AddressSanitizerとUndefinedBehaviorSanitizerを使います。
- 各pointerのownershipを文書化します。