C++语言一些可变的活生生的例子

发布于 2024-08-24 14:58:43 字数 169 浏览 5 评论 0原文

有人可以展示一个 mutable 关键字在 const 函数中使用时的使用实例,并在一个实例中解释一下 mutable > 和 const 函数,以及 volatile 成员和函数的区别。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紫南 2024-08-31 14:58:51

我曾经用它来实现记忆化

I used it once to implement memoization.

最偏执的依靠 2024-08-31 14:58:50

您可以在计数器上使用 mutable 来跟踪通过 const 访问器访问类成员的次数。

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

满栀 2024-08-31 14:58:48

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

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

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 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;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文