LoginSignup
4
2

More than 3 years have passed since last update.

勉強記録 12日目 〜mutable修飾子〜 - Effective C++ 第3版 -

Posted at

 はじめに

Effective C++ 第3版の3項14ページから勉強していきます。
今回は、「mutable修飾子」についです。

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

mutable修飾子

mutable修飾子とは?

前回の投稿で、メンバ関数にconst修飾子を付けると、メンバ関数内でメンバ変数を変更していけないということを勉強しました。

class ClassA {
 public:
  explicit ClassA(int x, int y) : x_(x), y_(y){};
  void       testFunc() const;
  int        getX() { return x_; };
  int        getY() { return y_; };

 private:
  int         x_;
  int         y_;
};

void ClassA::testFunc() const {
  std::cout << __func__ << std::endl;
  // x_ = 4;  // コンパイルエラー      // constメンバ関数内で、メンバ変数x_を変更したため
  // y_ = 3;  // コンパイルエラー      // constメンバ関数内で、メンバ変数y_を変更したため
}

上のコードのように、constメンバ関数 testFunc 内で、メンバ変数 x_, y_ を変更しようとすると、コンパイルエラーとなります。
しかし、const メンバ関数内でも、メンバ変数を変更(書き換え)したいときがあります。
このような場合に、 mutable修飾子をメンバ変数に付けます。

class ClassA {
 public:
  explicit ClassA(int x, int y) : x_(x), y_(y){};
  void       testFunc() const;
  int        getX() { return x_; };
  int        getY() { return y_; };

 private:
  mutable int    x_;  // mutable修飾子を付ける
  int            y_;
};

void ClassA::testFunc() const {
  std::cout << __func__ << std::endl;
  x_ = 4;       // constメンバ関数内で、メンバ変数x_を変更しているが、x_に mutable修飾子を付けているため変更可能
  // y_ = 3;  // コンパイルエラー      // constメンバ関数内で、メンバ変数y_を変更したため(mutable修飾子が付いていない)
}

上のコードのように、mutableを付けることで、constメンバ関数内でもメンバ変数を変更できていることが分かる。

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

サンプルコード

3_const_mutable.cpp
#include <iostream>

class ClassA {
 public:
  explicit ClassA(int x, int y) : x_(x), y_(y){};
  void testFunc() const;
  int  getX() { return x_; };
  int  getY() { return y_; };

 private:
  mutable int x_; // この変数は、constメンバ関数
  int         y_;
};

void ClassA::testFunc() const {
  std::cout << __func__ << std::endl;
  x_ = 4;
  // y_ = 3; // コンパイルエラー
}

int main(int argc, char* argv[]) {
  std::cout << "3_const_mutable.cpp" << std::endl;
  ClassA cc(1, 2);
  cc.testFunc();
  std::cout << "x : " << cc.getX() << std::endl;
  std::cout << "y : " << cc.getY() << std::endl;
}

実行結果

3_const_mutable.png

参考文献

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

4
2
1

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
4
2