今天在研究 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”,是以無法對其進行修改。
輸出結果如下:
