cpp / intermediate
Snippet
The 'mutable' Keyword
The mutable keyword allows a specific member of a class to be modified even if the object is accessed through a const reference or inside a const member function.
snippet.cpp
1
2
3
4
5
6
7
8
class Image {mutable bool cacheValid = false;public:void render() const {// Perform heavy rendering...cacheValid = true; // Allowed despite const function}};
Breakdown
1
mutable bool cacheValid
Marks the variable as modifiable within const contexts.
2
void render() const
A member function that promises not to modify the logical state of the object.