In C++, a developer could define a “const method”. This “const method” is useful to guarantee that the method will not alter your variable.
In the world of encapsulation, it helps developers to develop secure and understandable code. It guarantees that the method will not alter the concerned object. It gives a mark of confidence and improve the code cleanliness! We will see during this post how to improve your code quality with the keyword “Mutable”!
mutable – “permits modification of the class member declared mutable even if the containing object is declared const.”
In my previous post about the "const" case in C++, I quickly introduced this keyword. Let's see how to use it!
The issue
As I featured previously, C++ developers creates classes with several encapsulated variable (obviously). Sometimes, they declare a special method type, “the const method”:
This technique guarantees a method which return data and does not modify the object. It is useful for code quality and easy maintenance. A fresh developer can immediately see the purpose of the method. Overall, he can exploit it without unexpected knock-backs.
However, sometime, we can have a requirement to modify one or multiple variables. The best example is the mutex usage.
The Solution
The solution is the keyword “mutabe”.
This simple code example does not compile without the “mutable” keyword (try it!). It is due to the mutex which is acquired and released during the process.
However, should we sacrifice the code cleanliness? Should we convert the function as “no-const”? No, the “mutable” type specifier is a great solution! It specifies that your variable can be altered even in an object declared as const!
Most of the time, a mutex will be mutable. Because it is really helpful to consider a “const” as thread safe. The mutable keyword helps you to use internal mutex in const method.
It is the first post of my website for 2021. Many thanks to continue reading my blog. I wish you all the best for the New Year 2021!