mutable大概两种用法
第一种,若想在GetName中对一个私有成员变量进行更改,那么只能将其设置为mutable.
class test
{
private:
std::string m_name;
mutable int m_count;
public:
const std::string & GetName() const
{
m_count++;
return m_name;
}
};
int main()
{
const test t;
t.GetName();
return 0;
}
第二种,
#include<iostream>
#include<string>
int main()
{
int x = 0;
auto func = [=]() mutable
{
x++;
std::cout << x << std::endl;
};
func();
std::cout << x << std::endl;
return 0;
}
给你五秒钟猜猜运行结果。
5
4
3
2
1
如果lambda表达式以传值的方式,传入x那么在表达式体内就不能对x进行更改。如果以传址的方式进行传入,那么x的数值会改变。
而将其设置为mutable,这样做的本质是将x赋予新值,并且将新值输出。
如
#include<iostream>
#include<string>
int main()
{
int x = 0;
auto func = [=]()
{
int y = x;
y++
std::cout << y << std::endl;
};
func();
return 0;
}
当使用lambda表达式时,若想使用时改变,但是不改变其本体,就可以声明为mutable辣!