C++关键字mutable

今天在研究 G++ 2.91.57 源码中auto_ptr智能指针的时候,发现mutable这个从没用过的关键字,整理一下,以备后用。

mutable 意为“可变的、意变的”。被mutable关键字修饰的变量,将永远处于可变状态,即使在一个const函数中,例如:


#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

class Base
{
public:
Base(string msg, int n):strMsg(msg), nCount(n) {}

void changeMsg() const
{
strMsg = "Hello ddj";
//nCount = 12;                   
}

void print() const
{
cout<<strMsg<<"   "<<nCount<<endl;
}

private:
mutable string strMsg;
int nCount;
};


int _tmain(int argc, _TCHAR* argv[])
{
Base b("ddj", 24);
b.print();


b.changeMsg();
b.print();

system("pause");
return 0;
}


声明变量strMsg为mutable,这样在changeMsg()中该值可以改变成“Hello ddj”。 

而nCount由于是普通成员变量,如果在changeMsg()中修改该值时,编译时VS2010会报错:error C3490: 由于正在通过常量对象访问“nCount”,因此无法对其进行修改。


输出结果如下:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值