static mutable member variables in C++?

一笑奈何 提交于 2021-02-07 11:47:09

问题


why or for what reason is it not possible to declare a class member variable in C++ as static mutable? Something like

static mutable int t; //This won't compile

For me, there is no reason to ban such declarations. E.g. for reasons like maintaining a global class-wide statistics, it may be convenient to have static variable that can be altered by (logically) const methods. So either this is sort of a misdesign in C++ and unnecessarily complicated, or there is a practical or theoretical reason which I cannot see.


回答1:


Non-const static members of the class can already be modified by any (const and non-const) methods of the class. There's no need and no point in declaring it with mutable. That would achieve absolutely nothing.




回答2:


The mutable keyword allows a "const" and therefore non-static member function to change non-static member variables marked as such (i.e., mutable). Static functions cannot be const and const member functions can change non-const static members. I know this is somewhat confusing, but it is because of this that there is no need to allow a mutable static member variable.



来源:https://stackoverflow.com/questions/3951686/static-mutable-member-variables-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!