ポインタとメモリ

ポインタとアドレス

Pointerは互換型objectのaddressを保持します。

ポインタとアドレスとは?

Pointerは互換型objectのaddressを保持します。

アドレスを保存しdereferenceして元のobjectを変更します。

重要なポイント

  • ポインタは生存中の互換オブジェクトを指すかnullである必要があります。
  • 所有するallocationは一度だけ解放します。
  • ownershipとconstを明確に表現します。

CとC++のコード例

C
実行 →
main.c
#include <stdio.h>

int main(void) {
    int score = 70;
    int *score_ptr = &score;
    *score_ptr += 5;
    printf("score=%d same-address=%s\n", score,
           score_ptr == &score ? "yes" : "no");
    return 0;
}
期待される出力
score=75 same-address=yes
C++
実行 →
main.cpp
#include <iostream>

int main() {
    int score = 70;
    int* score_ptr = &score;
    *score_ptr += 5;
    std::cout << "score=" << score << " same-address="
              << std::boolalpha << (score_ptr == &score) << '\n';
}
期待される出力
score=75 same-address=true

CとC++の比較

Cはraw pointerを直接使います。C++でもnon-owning accessに使いますが、null不要ならreferenceが適します。

C

ownershipとcleanupはプログラマが守る規約です。

C++

containerとRAIIがownershipとcleanupをlifetimeに結び付けます。

練習課題

両方を実行して変更し、言語ごとの保証を確認します。

  • nullとallocation失敗をテストします。
  • AddressSanitizerとUndefinedBehaviorSanitizerを使います。
  • 各pointerのownershipを文書化します。