C++语言一些可变的实例

nav*_*ekh 3 c++ const mutable volatile

有人可以显示mutable关键字用法的实例,当它在const函数中使用时,在实例中解释关于mutableconst函数以及volatile成员和函数的差异.

for*_*idt 6

您可以对允许在const对象实例中修改的变量使用mutable.这称为逻辑常量(与按位常量相反),因为对象从用户的角度来看没有改变.

例如,您可以缓存字符串的长度以提高性能.

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;
};
Run Code Online (Sandbox Code Playgroud)

  • 我使用它们的其他地方是迭代器,其中const引用迭代器值,而不是迭代器索引(必须是可变的) (2认同)
  • @Alex:`const iterator = const_iterator`相当于`T*const = const T*`,由于正当理由无效. (2认同)