views:

193

answers:

3

Respected sir ,

I need some help for mutable keyword it is used in a const function and please any body explain for the live example about the mutable and constant function and also diff. for the volatile member and function please help me

in Advance Thank you,

+5  A: 

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;
};
mxp
other place I use them is in iterators, where const refers to iterator values, rather than iterator index (which must be mutable)
aaa
so you define const iterators to be const_iterators... I never understood why there were two different types.
Alexandre C.
@Alexandre: Because the constness of the iterator and the constness of the value it references are two very different things.
Georg Fritzsche
yes I pretty much understand that. But your solution is more consistent with the behaviour of T* and const T*, and I don't understand why STL designers didn't introduce const iterator = const_iterator semantics in the first place.
Alexandre C.
@Alex: `const iterator = const_iterator` is equivalent to `T* const = const T*`, which is invalid for good reasons.
Georg Fritzsche
A: 

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

tojas
+1  A: 

I used it once to implement memoization.

Alexandre C.