naval Parekh
naval Parekh

Reputation: 51

C++ language some live examples for mutable

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.

Upvotes: 3

Views: 1088

Answers (3)

Alexandre C.
Alexandre C.

Reputation: 56976

I used it once to implement memoization.

Upvotes: 1

tojas
tojas

Reputation: 225

You can use mutable on a counter tracking the number of time a Class member is accessed through a const accessor.

Upvotes: 1

foraidt
foraidt

Reputation: 5709

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;
};

Upvotes: 6

Related Questions