Members in the function definition static variable (insecurity, shared between objects)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/u012317833/article/details/41011997
definition of static member variables within the function

Local variables can be static member function of. If a member of a local variable in the function is defined as static variables, all objects of that class when calling this member function to share this variable.


class C
{
public:
void m();
private:
int x;
};

void C::m()
{
static int s=0;
cout<<++s<<endl;
}

int main()
{
C c1,c2;
c1.m(); //1
c2.m(); //2
c1.m(); //3
return 0;
}

This example defines a static member function in the variable s m, since the s defined within the block, the block that has a range, so it can only be accessed internally m. M once per call, s time will increase accordingly. And because m is a member of C functions, so all the objects C are sharing this static local variable. In this way, each call access to m are the same s. In contrast, for non-static local variable x, each object has a C x. Therefore, the first call in main c1.m () will be from 0 to 1 s, call c2.m () will be increased from 1 to 2 s, the second call c2.m () increased from 2 to s to 3.
----------------
Disclaimer: This article is CSDN blogger "than not than not" original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/u012317833/article/details/41011997

Guess you like

Origin www.cnblogs.com/findumars/p/11599032.html