#3(の1)可能ならいつでも const を使う.

Effective C++ 3項の内容です.

const の使い方一覧

constがとても大事なことは,Effective C++も言っているし,とても良くわかるんですが,constの位置によってconstの対象が変わるのがなかなか覚えられません...一通りリストアップします.

"const" for 変数編

変数に対しての const 宣言としては,主に下記の5つがあります.Effective C++では,下記のような覚え方が提唱されていました.
アスタリスク(*)よりも const が右側に来ていたら,データが const.左側に来ていたら,ポインタが const ということだそうです.」

  • 1.データがconst

const int a = 0;

  • 2.ポインタがconst,ポインタの指すデータは非const

int * const a;

  • 3.ポインタが非const,ポインタの指すデータはconst

int const * a

  • 4.ポインタもconst,ポインタの指すデータもconst

int const * const d = 10

ということで,サンプルコードです.

#include <iostream>

int main(int, char**) {

  std::cout << "Effective C++ 3項" << std::endl;

  // 1. データが const
  // 変数に対するconst宣言
  const double a = 0;

  // error: assignment of read-only variable ‘a’
  // a = 1;

  // 2. ポインタが非 const, データが const
  const int *b = 0;

  // データの更新は許されない.
  // error : assignment of read-only location ‘* b’
  //*b = 10;

  // ポインタの更新は許される.
  // This is possible.
  b = nullptr;

  // 3. ポインタが const,データが 非const
  int * const c = nullptr;
  int d = 0;

  // データの更新は許される.
  *c = 100;

  // ポインタの更新は許されない.
  // error : assignment of read-only variable ‘c’
  // c = &d;

  // 4. ポインタ,データともに const
  int const * const e = 0;
  // error : assignment of read-only location ‘*(const int*)e’
  //*e = 10;

  // error: assignment of read-only variable ‘e’
  // e = nullptr;

  return 0;
}