多次元配列
組み込み2D配列は両言語で行単位の連続メモリです。
多次元配列とは?
組み込み2D配列は両言語で行単位の連続メモリです。
Row-majorのmatrixを走査して行合計を求めます。
重要なポイント
- ポインタは生存中の互換オブジェクトを指すかnullである必要があります。
- 所有するallocationは一度だけ解放します。
- ownershipとconstを明確に表現します。
CとC++のコード例
C
main.c
#include <stdio.h>
int main(void) {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int row = 0; row < 2; ++row) {
int total = 0;
for (int column = 0; column < 3; ++column) total += matrix[row][column];
printf("row %d=%d\n", row, total);
}
return 0;
}
row 0=6
row 1=15
C++
main.cpp
#include <array>
#include <iostream>
int main() {
std::array<std::array<int, 3>, 2> matrix{{{{1, 2, 3}}, {{4, 5, 6}}}};
for (std::size_t row = 0; row < matrix.size(); ++row) {
int total = 0;
for (int value : matrix[row]) total += value;
std::cout << "row " << row << '=' << total << '\n';
}
}
row 0=6
row 1=15
CとC++の比較
C関数は先頭以外のdimensionを知る必要があります。std::arrayはdimensionを型に保持しatも使えます。
C
ownershipとcleanupはプログラマが守る規約です。
C++
containerとRAIIがownershipとcleanupをlifetimeに結び付けます。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- nullとallocation失敗をテストします。
- AddressSanitizerとUndefinedBehaviorSanitizerを使います。
- 各pointerのownershipを文書化します。