34 The Mutable Keyword
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
本文来自博客园,作者:zhihh,转载请注明原文链接:https://www.cnblogs.com/zhihh/p/18395056/cpp-series-34-mutable
浙公网安备 33010602011771号