Can someone show a live example of the usage of mutable keyword, when it is used in a const function and explain in a live example about the mutable and const function and also difference for the volatile member and function.
You can use mutable for variables that are allowed to be modified in const object instances. This is called logical constness (opposed to bitwise constness) as the object has not changed from the user's point of view.
You can for example cache the length of a string to increase performance.
class MyString
{
public:
...
const size_t getLength() const
{
if(!m_isLenghtCached)
{
m_length = doGetLength();
m_isLengthCached = true;
}
return m_length;
}
private:
sizet_t doGetLength() const { /*...*/ }
mutable size_t m_length;
mutable bool m_isLengthCached;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With