The Mutable Keyword
Referece: The Mutable Keyword in C++
mutable
, it declares something that can change.
with const
In debug mode, if you want to know how many time a const declared method was called, dowever, becauseof const
, you can not modify any of the class members, so you can not record the calling times. Now, you got the keyword mutable
, it allowed that method to modify mutable
declared class members.
#include <iostream>
#include <string>
class Entity
{
private:
std::string m_Name;
mutable int m_DebugCount = 0;
public:
const std::string& GetName() const
{
m_DebugCount++;
return m_Name;
}
};
int main()
{
const Entity e;
e.GetName();
}
with lamdas
A lamda is basically like a little throwaway function that you write and assign to a variable quikly.
int x = 8;
auto f = [=]()
{
x++;
std::cout << x << std::endl;
};
f();
// error: 'x': a by copy capture cannot be modified in a non-mutable lambda.
you can fix it with a additional local variable y
,
int x = 8;
auto f = [=]()
{
int y = x;
y++;
std::cout << y << std::endl;
};
f();
but, it looks a little bit messy, especially there are lots of this kind of variables, so mutable
, use it to declare a mutable lambda. (complier would translate as same as what mentioned above)
int x = 8;
auto f = [=]() mutable
{
x++;
std::cout << x << std::endl;
};
f();
std::cout << x << std::endl;
// output:
// 9 (by f())
// 8
标签:std,const,Keyword,int,34,mutable,Mutable
From: https://www.cnblogs.com/zhihh/p/18395056/cpp-series-34-mutable