LoginSignup
1
1

More than 3 years have passed since last update.

勉強記録 8日目 〜ポインタのconstとデータのconst〜 - Effective C++ 第3版 -

Posted at

 はじめに

Effective C++ 第3版の3項8ページから勉強していきます。
今回は、「ポインタのconstとデータのconst」についです。

Effective C++ 第3版 - 3項 可能ならいつでもconstを使おう -

ポインタのconstとデータのconst

constを付ける利点

constを付ける利点は、特定のオブジェクトについて、「変更してはいけない」という意味的な制約をはっきりさせ、制約を破るとコンパイラが知らせてくれる点です。
また、constにより、他のプログラマにも、指定したオブジェクトの値を変更しないように知らせることできる。
そのため、オブジェクトの値を変更するつもりがないのであれば、constを付けた方が良い。

constが使える範囲

constは、驚くほど広い範囲で使用されます。
クラス外では、グローバルな定数、あるいは、名前空間内での定数でconstを使える。
また、ファイル、関数、ブロックのstaticオブジェクトにも付けることができる。
クラス内では、static・非static双方のデータメンバに使える。
また、ポインタに使って、「ポインタそのものが変更不可」なのか、「ポインタの指すデータが変更不可」なのか、あるいは両方なのかを指定することができる。

以下にポインタにconstを付けた場合、「ポインタそのものが変更不可」なのか、「ポインタの指すデータが変更不可」なのかを示す。

int *p1_x = &x;              // ポインタは非const
                             // データも非const
const int *p2_x = &x;        // ポインタは非const
                             // データはconst
int *const p3_x = &x;        //  ポインタはconst
                             // データは非const
const int *const p4_x = &x;  // ポインタはconst
                             // データもconst

上に、示す通り、constがアスタリスク(*)の右にあるのか左にあるかで、「ポインタが変更不可」なのか、「ポインタの指すデータが変更不可」なのかが区別できる。

以下に、勉強で使用したコードを示します。

サンプルコード

#include <iostream>

int main(int argc, char *argv[]) {
  std::cout << "3_const_tutorial.cpp" << std::endl;
  int x = 5;

  int *p1_x = &x;              // ポインタは非const
                               // データも非const
  const int *p2_x = &x;        // ポインタは非const
                               // データはconst
  int *const p3_x = &x;        //  ポインタはconst
                               // データは非const
  const int *const p4_x = &x;  // ポインタはconst
                               // データもconst

  int x2 = 3;
  *p1_x  = x2;
  p1_x   = &x2;

  // *p2_x = x2; // コンパイルエラー
  p2_x = &x2;

  *p3_x = x2;
  // p3_x  = &x2; // コンパイルエラー

  // *p4_x = x2;   // コンパイルエラー
  // p4_x  = &x2;  // コンパイルエラー
}

実行結果

参考文献

https://www.amazon.co.jp/gp/product/4621066099/ref=dbs_a_def_rwt_hsch_vapi_taft_p1_i0

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1