次の例を検討してください。
#include <iostream>
using std::endl;
using std::cout;
class my_class {
private:
int _expensive_count_operation() const {
return 10;
}
bool cached;
int last_count;
public:
my_class() { cached = false; }
int get_count() {
if (cached) {
cout << "Got count from cache." << endl;
return last_count;
}
cout << "Computing count." << endl;
last_count = _expensive_count_operation();
cached = true;
return last_count;
}
int get_const_count() const {
my_class* _this = const_cast<my_class*>(this);
if (cached) {
cout << "Got count from cache." << endl;
return last_count;
}
cout << "Computing count." << endl;
_this->last_count = _expensive_count_operation();
_this->cached = true;
return last_count;
}
};
int main() {
my_class my_object1,my_object2;
int count;
count = my_object1.get_count();
cout << "Count: " << count << endl;
count = my_object1.get_count();
cout << "Count: " << count << endl;
count = my_object2.get_const_count();
cout << "Count: " << count << endl;
count = my_object2.get_const_count();
cout << "Count: " << count << endl;
}
get_const_count メソッドで const_cast を使用すると、メソッド const を保持できます。問題は、これに関連する危険性は何ですか? また、このクラスの const インスタンス (またはそれらへのポインター) を使用できなくなることに伴う危険性と比較して、どうすればよいでしょうか? さらに良いことに、より良いアプローチはありますか?
キャッシングを使用して最適化したいコードを記述した場合、このような状況に陥ることがよくあります。問題は、const 宣言を削除し、その変更を残りのコード ベースに反映させる必要があることです。