用mutable关键字修饰的变量,将会处于可变状态,可以被修改。
- const函数中
class mutable_test {
private:
int test_number_ = 0;
public:
int GetTestNumber() const {
return test_number_++;
}
};
错误 C3490 由于正在通过常量对象访问“test_number_”,因此无法对其进行修改
此时用mutable修饰test_number_即可解决此问题(此处不讨论为何如此写,仅作为验证)
class mutable_test {
private:
mutable int test_number_ = 0;
public:
int GetTestNumber() const {
return test_number_++;
}
};
int main()
{
mutable_test test;
std::cout << test.GetTestNumber() << std::endl;
}
- const 类
class mutable_test {
public:
int test_number_ = 0;
};
class mutable_test1 {
public:
mutable int test_number_ = 0;
};
int main()
{
const mutable_test test;
test.test_number_ = 1; //error:不能给常量赋值
const mutable_test1 test1;
test1.test_number_ = 1; //OK
}
- lambda表达式
int test_num = 1;
auto fun = [&]() {return test_num++; }; //OK
auto fun1 = [=]()mutable{return test_num++; };//OK
auto fun2 = [=]() {return test_num++; }; //error 无法在非可变lambda中修改通过复制捕获的值
test_num = 3;
std::cout << fun() << std::endl; //3
std::cout << fun1() << std::endl;//1
补充一下:通过值传递的lambda表达式在定义的时候值就已经确认了,在定义到真正调用过程中即使变量发生了变化(test_num = 3)也不会影响到lambda里面的值
一个变量不能同时用const和mutable来修饰