天天看点

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”,因此无法对其进行修改。

输出结果如下:

C++关键字mutable

继续阅读