C++中的mutable

文章讲述了C++中的mutable关键字,即使在const方法中,允许对某些mutable成员变量进行修改,如类Counter中的cache。const对象通常禁止修改,但mutable成员例外。
摘要由CSDN通过智能技术生成

mutable

在 C++ 中,mutable 关键字是用来说明即使一个对象是常量,对象内的某个成员变量也可以被修改。通常,这个关键字用于类的成员变量。让我给你一个简单的例子来说明这个概念。

考虑一个类 Counter,它有一个成员变量 value 来计数,还有一个 mutable 成员变量 cache,用于缓存一些值。即使在一个 const 方法中,你仍然可以修改 cache

#include <iostream>

class Counter {
public:
    Counter() : value(0), cache(0) {}

    void increment() {
        ++value;
        updateCache();
    }

    int getValue() const {
        // Even though this method is const, it can still change the cache.
        updateCache();
        return value;
    }

private:
    int value;

    // Declare cache as mutable
    mutable int cache;

    void updateCache() const {
        // We can modify the cache because it is mutable
        cache = value * value;
    }
};

int main() {
    const Counter cnt;
    std::cout << "Initial value: " << cnt.getValue() << std::endl;
    
    // Error: increment() is a non-const function, cannot be called on a const object.
    // cnt.increment(); 

    // Note: The above line will cause a compile error because increment() is not a const
    // method, and we're trying to call it on a const instance of Counter.

    return 0;
}

在这个例子中,即使 getValue() 是一个 const 方法,它仍然可以调用 updateCache() 去更新 cache 变量,因为 cache 被声明为 mutable

请注意,在 main() 函数中,我们创建了一个 const Counter 对象。通常,你不能在一个 const 对象上调用任何非 const 方法,也不能修改它的任何成员变量。但是由于 cachemutable 的,getValue() 方法可以修改它。

在上面的代码中,如果你尝试取消注释 main() 函数中的 cnt.increment();,你会得到一个编译错误,因为 increment() 不是一个 const 方法,因此它不能在 const 对象 cnt 上被调用。但是 getValue() 可以被调用,并且它可以修改 mutable 成员 cache

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值