2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c++ > mutable > 同時に呼び出すかどうか?

2
Last updated at Posted at 2015-08-11

mutableの必要性がいまいち理解できていない。
メンバ変数を変更するのであれば、メソッドからconstをはずせばいいのかと勝手に思っていた。

以下を見つけた。
http://d.hatena.ne.jp/yohhoy/20130803/p1

Polygon::get_area()はconstメンバ関数となっているため、呼び出し側は複数スレッドから同時に同メンバ関数を呼び出すことができる(とC++11 constセマンティクスにより解釈する)。get_area()メンバ関数の内部実装では、mutableなstd::mutexオブジェクトを利用した排他制御を行っている(C++11 constセマンティクスを守るためにこう実装する義務がある)。

一方Polygon::append()は非constメンバ関数のため、呼び出し側はこのメンバ関数を他メンバ関数と同時に呼び出す事はない(とC++11 constセマンティクスにより制限される)。このため、cached_area_メンバ変数に対して排他制御なしに変更操作を行っている(これが安全であるとC++ constセマンティクスにより保証される)。

まだきちんと理解できていない。
理解にもう少し時間が必要だろう。

2
1
6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?