Can someone show a live example of the usage of mutable
keyword, when it is used in a cons开发者_JAVA百科t
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;
};
You can use mutable on a counter tracking the number of time a Class member is accessed through a const accessor.
I used it once to implement memoization.
精彩评论