mutable关键字
两种用法:一种在const方法中用于声明可以改变类成员变量,一种在lambda表达式中用于引用传递作为局部变量来使用。
一:
class Entity {
private:
std::string m_Name;
mutable int m_DebugCount = 0;
public:
const std::string& GetName() const {
m_DebugCount++;
return m_Name;
}
};
使用场景:比如在实际项目中,想统计一个const过后的类对象的某个方法的使用次数,但如果将变量声明到类外,容易混乱,而声明在类中又会报错,所以使用关键字mutable后,便可以在类中声明可改变的变量。
二:
int x = 8;
auto f = [=]() mutable {
x++;
std::cout << x << std::endl;
};
f();
若不适用mutable关键字,x在表达式内会报错(这里不太懂,等深入学习了lambda表达式后再进行回顾)
构造函数初始化列表
class Example {
public:
Example() {
std::cout << "Created Entity!" << std::endl;
}
Example(int x) {
std::cout << "Created Entity with " << x << "!!" << std::endl;
}
};
class Entity {
private:
std::string m_Name;
int m_Score;
Example m_Example;
mutable int m_DebugCount = 0;
public:
Entity()
: m_Name("lhx"), m_Score(0),m_Example(8)
{
m_Name = std::string("unknown");
m_Example = Example(8);
}
Entity(const std::string& name) {
m_Name = name;
}
const std::string& GetName() const {
m_DebugCount++;
return m_Name;
}
};
int main() {
Entity e;
}
构造函数初始化列表需要按照声明顺序来写,若打破这个规则,可能会造成许多依赖问题。
另外若类中有成员变量为其他类的对象时,若需要在构造函数中初始化赋值,假如不使用构造函数初始化列表,其他类的对象会初始化两次,造成性能的浪费。
如果使用构造函数初始化列表则只会初始化一次: