C++ const和mutable
const和mutable
这里只说const在c++中的特殊用法。用const修饰函数的成员函数。
被const修饰的成员函数无法修改函数内的其他成员。可以认为这个函数变成了一个“只读”的状态。
Like this:
// 注意const在括号后面,不要写成const xx xxx(){...}了
int getStatus() const{
return m_status;
}
而mutable意为“可变”,与const相反。上面说到被const修饰的成员函数无法修改函数内的其他成员。但是如果有一个成员函数被mutable修饰,就可以在const函数内修改值(可以理解为抵消了const的效果)。
下面是一个const函数和mutable的例子:
#include<iostream>
using namespace std;
class Entity {
private:
string m_name;
mutable int test = 0;
public:
Entity(string name = "unnamed") {
m_name = name;
}
string getName() const {
//m_name = "Test"; 不能修改,成员函数有const修饰
test = 1; // 可以修改,因为有mutable修饰
/*
虽然在const函数中尝试改变某个变量似乎没什么意义
但是有时候在debug时可以修改某个值可能方便我们调试,这完全没什么问题
*/
return m_name;
}
string getName() {
// 一个没有const修饰的版本
// 如果只有这个版本,没有上面那个版本,printName函数就会报错
return m_name;
}
void setName(string name = "unnamed") {
m_name = name == "unnamed" ? m_name : name;
}
};
void printName(const Entity &e) {
// const Entity 只能调用有const修饰的成员
cout << e.getName() << endl;
}
int main() {
Entity e;
printName(e);
e.setName("The World");
printName(e);
return 0;
}
ps:虽然在const函数中尝试改变某个变量似乎没什么意义,但是有时候在debug时可以修改某个值可能方便我们调试,这完全没什么问题。举个例子, 在debug中, 有时我们想知道这个const函数被调用了多少次. 然后弄个计数器, 这个计数器要在const函数中改变值, 就需要用mutable标记.