Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static mutable member variables in C++?

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.

like image 644
shuhalo Avatar asked Oct 17 '10 02:10

shuhalo


People also ask

Are static variables mutable?

Static variables can be mutable.

What is a static member variable?

Static variables are initialized to 0. It is initialized only once. Throughout the program, only one copy of the static member variable is created for the entire class hence static member variables are also called class variables. It is shared by all instances of the class.

Can static be mutable?

Static data members cannot be mutable. Static data members of a class in namespace scope have external linkage if the class itself has external linkage (is not a member of unnamed namespace).

What are static members in C?

When the member variables are declared with a static keyword in a class, then it is known as static member variables. They can be accessed by all the instances of a class, not with a specific instance. The member function of a class declared with a static keyword is known as a static method.


1 Answers

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.

like image 188
AnT Avatar answered Sep 20 '22 12:09

AnT