C ++ language - some living examples for mutable

Can someone show a live example of the use of a keyword mutablewhen it is used in a function constand explains in a live example about the function mutableand const, as well as the difference for the volatilemember and the function.

+3
source share
3 answers

You can use mutable for variables that can be changed in instances of const objects. This is called a logical constant (the opposite of a bit constant), since the object has not changed from a user point of view.

You can, for example, cache line lengths to improve 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;
};
+6

mutable , const.

+1

I used it once to implement memoization .

+1
source

Source: https://habr.com/ru/post/1736779/


All Articles