考虑以下示例:
#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 声明并将该更改传播到代码库的其余部分。