c++關鍵字mutable深入解析
C++中的mutable關鍵字
mutalbe的中文意思是“可變的,易變的”,跟constant(既C++中的const)是反義詞。
在C++中,mutable也是為了突破const的限制而設置的。被mutable修飾的變量,將永遠處于可變的狀態(tài),即使在一個const函數(shù)中。
我們知道,被const關鍵字修飾的函數(shù)的一個重要作用就是為了能夠保護類中的成員變量。即:該函數(shù)可以使用類中的所有成員變量,但是不能修改他們的值。然而,在某些特殊情況下,我們還是需要在const函數(shù)中修改類的某些成員變量,因為要修改的成員變量與類本身并無多少關系,即使修改了也不會對類造成多少影響。當然,你可以說,你可以去掉該函數(shù)的const關鍵字呀!但問題是,我只想修改某個成員變量,其余成員變量仍然希望被const保護。
經典的應用場景比如說:我要測試一個方法的被調用次數(shù)。
class Person { public: Person(); ~Person(); int getAge() const; /*調用方法*/ int getCallingTimes() const; /*獲取上面的getAge()方法被調用了多少次*/ private: int age; char *name; float score; int m_nums; /*用于統(tǒng)計次數(shù)*/ };
最普遍的作法就是在getAge()的方法體內對m_nums這個變量進行加+1,但是getAge()方法又是const方法,無法修改m_nums這個變量,我又不想去掉const關鍵字讓別人能夠修改age等成員變量,這個時候mutable關鍵字就派上用場了:
#include <iostream> class Person { public: Person(); ~Person(); int getAge() const; /*調用方法*/ int getCallingTimes() const; /*獲取上面的getAge()方法被調用了多少次*/ private: int age; char *name; float score; mutable int m_nums; /*用于統(tǒng)計次數(shù)*/ }; Person::Person() { m_nums = 0; } Person::~Person(){} int Person::getAge() const { std::cout << "Calling the method" << std::endl; m_nums++; // age = 4; 仍然無法修改該成員變量 return age; } int Person::getCallingTimes()const { return m_nums; } int main() { Person *person = new Person(); for (int i = 0; i < 10; i++) { person->getAge(); } std::cout << "getAge()方法被調用了" << person->getCallingTimes() << "次" << std::endl; delete person; getchar(); return 0; }
運行結果:
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
Calling the method
getAge()方法被調用了10次
這樣我們既保護了別的成員變量,又能夠使計數(shù)器的值進行累加。
需要注意的是:mutable不能修飾const 和 static 類型的變量。
1、關于mutable關鍵字
先說用法,mutable關鍵字只能修飾非靜態(tài)以及非常量成員變量,使用mutable修飾的成員變量在const函數(shù)中的值是可以修改的。
比如說下面的代碼:
class Demo { public : Demo() {} ~Demo() {} public : bool getFlag()const { m_nAccess++; return m_bFlag; } private : int m_nAccess; bool m_bFlag; }; int main() { return 0 ; }
編譯的時候會報錯,因為const成員函數(shù)修改了成員變量,但是如果聲明m_nAccess的時候加上關鍵字mutable就可以了。
PS:一個對象的狀態(tài)由該對象的非靜態(tài)數(shù)據(jù) 成員決定,所以隨著數(shù)據(jù)成員的改變, 對像的狀態(tài)也會隨之發(fā)生變化! 如果一個類的成員函數(shù)被聲明為const類型,表示該函數(shù)不會改變對象的狀態(tài),也就是該函數(shù)不會修改類的非靜態(tài)數(shù)據(jù)成員.但是有些時候需要在該類函數(shù)中對類的數(shù)據(jù)成員進行賦值.這個時候就需要用到mutable關鍵字了。
相關文章
Qt動態(tài)庫調用宿主進程中的對象方法純虛函數(shù)使用
這篇文章主要為大家介紹了Qt動態(tài)庫調用宿主進程中的對象方法純虛函數(shù)使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08