C++ 关键词 mutable

Mutable 关键词的作用是:可以在常函数中被修改其值。

Mutable适用的场合极少,因此当你觉得你需要使用该关键词时,请再三思考!

下面列出几种Mutable适用的场合:

1. You have a constant object, but for debugging purposes want to track how often a constant method is called on it. Logically you're not changing the object. Note that if you're making decisions in your program based on a mutable variable, you've almost certainly violated logical constness and need to rethink things.

class Employee {
public:
Employee(const std::string & name)
: _name(name), _access_count(0) { }
void set_name(const std::string & name) {
_name = name;
}
std::string get_name() const {
_access_count++;
return _name;
}
int get_access_count() const { return _access_count; }

private:
std::string _name;
mutable int _access_count;
}

2. As a more complex example, you might want to cache the results of an expensive operation:

class MathObject {
public:
MathObject() : pi_cached(false) { }
double pi() const {
if( ! pi_cached ) {
/* This is an insanely slow way to calculate pi. */
pi = 4;
for(long step = 3; step < 1000000000; step += 4) {
pi += ((-4.0/(double)step) + (4.0/((double)step+2)));
}
pi_cached = true;
}
return pi;
}
private:
mutable bool pi_cached;
mutable double pi;
};

Now we don't calculate pi until someone asks for it, but when they do we cache the result, which is good because we're calculating it in a really slow and stupid way. Logically the function is still const (pi isn't about to change).

Ultimately you almost certainly do not need mutable at any given moment. I've gone years between wanting the mutable keyword. If you think you need mutable, think twice. Be sure that the object will still be logically constant, even as its internals change.


链接:http://www.highprogrammer.com/alan/rants/mutable.html


原文链接: https://www.cnblogs.com/iamsailing/archive/2012/02/21/2360757.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 关键词 mutable

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/42125

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午6:56
下一篇 2023年2月8日 下午6:56

相关推荐