C++之mutable

mutable大概两种用法

第一种,若想在GetName中对一个私有成员变量进行更改,那么只能将其设置为mutable.

class test
{
private:
    std::string m_name;
    mutable int m_count;
public:
    const std::string & GetName()   const
    {
        m_count++;
        return m_name;
    }
};

int main()
{
    const test t;
    t.GetName();

    return 0;

}

第二种,

#include<iostream>
#include<string>


int main()
{


    int x = 0;
    auto func = [=]() mutable
    {
        x++;
        std::cout << x << std::endl;

    };

    func();
    std::cout << x << std::endl;

    return 0;

}

给你五秒钟猜猜运行结果。

5

4

3

2

1

 如果lambda表达式以传值的方式,传入x那么在表达式体内就不能对x进行更改。如果以传址的方式进行传入,那么x的数值会改变。

而将其设置为mutable,这样做的本质是将x赋予新值,并且将新值输出。

#include<iostream>
#include<string>


int main()
{


    int x = 0;
    auto func = [=]() 
    {
        int y = x;
        y++
        std::cout << y << std::endl;

    };

    func();


    return 0;

}

当使用lambda表达式时,若想使用时改变,但是不改变其本体,就可以声明为mutable辣!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值