mutable关键字详解与实战

在C++中mutable关键字是为了突破const关键字的限制mutable关键字mutable关键字,被mutable关键字修饰的成员变量永远处于可变的状态,即使是在被const修饰的成员函数中。

在C++中被const修饰的成员函数无法修改类的成员变量,成员变量在该函数中处于只读状态。然而,在某些场合我们还是需要在const成员函数中修改成员变量的值,被修改的成员变量与类本身并无多大关系,也许你会说,去掉函数的const关键字就行了。可问题是,我只想修改某个变量的值,其他变量希望仍然被const关键字保护。

现在有个场景,我们想获取函数被调用的次数,代码如下:

class Widget{
public:
Widget();
~Widget() = default;
int getValue() const;
int getCount() const;
private:
int value;
int count;
};

这里我们想要获取getValue函数被调用次数,普遍的做法是在getValue函数里对成员变量count进行加1处理,可是getValue被关键字const修饰啊,无法修改count的值。这个时候mutable派上用场了!我们用mutable关键字修饰count,完整代码如下:

#include 
class Widget{
public:
Widget();
~Widget() = default;
int getValue() const;
int getCount() const;
private:
int value;
mutable int count;
};
Widget::Widget() : value(1), count(0) { }
int Widget::getValue() const{
count++;
return value;
}
int Widget::getCount() const{
return count;
}
int main()
{
Widget w1;
for(int i = 0; i < 5; i++){
w1.getValue();
}
std::cout << w1.getCount() << std::endl;
return 0;
}

被mutable修饰的成员变量count在getValue函数里进行加1计数,编译运行输出如下:

5

既保护了其他成员变量,又能达到我们单独修改成员变量count值的目的。

C++11很吊的新特性!std::function

C++里std::enable_shared_from_this是干什么用的?

限时特惠:本站每日持续更新海量展厅资源,一年会员只需29.9元,全站资源免费下载
站长微信:zhanting688