"Reprint" The use of static in C + + detailed

Source: Internet
Author: User

Source:

http://blog.csdn.net/majianfei1023/article/details/45290467

There are three (specifically two) uses of the static keyword for C language:


1. Static local variables: used in the function body interior modification variables, the lifetime of such a variable longer than the function. 、

int foo () {      staticint1//  note:1      //int i = 1 ;   // note:2      1 ;       return i;  }  

To understand this usage, we first need to understand the memory distribution of C + + and the interval where static is located.

For a complete program, the distribution in memory is as follows:
1. Stack area: Automatically allocated by the compiler release, such as local variables, function parameters, are in the stack area. Frees up space as it functions to exit.
3. Heap area: Areas allocated and released by programmers, like malloc (c), new (C + +)
3. Global Data Zone (static zone): Global variables and static storage are placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another area adjacent. The program ends the release.
4. Code Area

So the static of the above note:1 is allocated in the global data area, so what does it mean to exist? And when did it initialize?

First answer the first question: the meaning of its existence is that it is initialized with the invocation of the first function, but is not destroyed with the call of the function (if the above note:1 is replaced with note:2, then I is allocated in the stack, and will be released with the end of Foo's call).
Then the second problem surfaced, it is the first call into the note:1 when the initialization (the interview was a pit, I actually said it was the beginning of the initialization, sweat!!) )。 And initialize only once, that is, the second time you call Foo (), will not continue to initialize, and will skip directly.


So what's the difference between defining a global variable and initializing it again, the result of calling Foo () is the same, but, using global variables, the variables are not part of the function itself, they are no longer controlled by the function, and the maintenance of the program is inconvenient.
Static local variables can solve this problem. Static local variables are saved in the global data area, not in the stack, and each time the value is persisted to the next call until the next time the new value is assigned.


So let's summarize the characteristics of static local variables (note:2 in parentheses, which is the contrast of local variables):
(1) The variable allocates memory in the global data area (local variables allocate memory in the stack area);
(2) A static local variable is first initialized when the program executes to the declaration of the object, that is, the subsequent function call is no longer initialized (local variables are initialized each time the function calls);
(3) Static local variables are generally initialized at the declaration, if not explicitly initialized, the program will be automatically initialized to 0 (local variables will not be initialized);
(4) It always resides in the global data area until the program finishes running. But its scope is a local scope, that is, it cannot be used outside the function body (local variables in the stack area, immediately after the end of the function to free memory);


2. Static global variable: defined in the function body, used to decorate the global variable, indicating that the variable is visible only in this file.

Static int 1;  // Note:3   // int i = 1;   // note:4      int foo ()  {      1;       return i;  }  

What is the difference between Note:3 and note:4? You call Foo (), and their results are the same no matter how many times they are called. That is, calling them in this file is exactly the same. So what is the difference between them?
File Isolation!

Assuming I have a file a.c, let's create a new B.C, which reads as follows.

//file A.C//static int n = 15; //Note:5intn = the;//Note:6//file B.C#include <stdio.h>extern intN; voidfn () {n++; printf ("After :%d\n", N); }      voidMain () {printf ("Before:%d\n", N);  FN (); }  

We first use Note:6, the non-static global variable, to find out that the output is:
Before:15
After:16


That is, our B.C uses the global variables defined by A.C through extern.
So let's change to using Note:5, that is, using static global variables.

GCC A.C b.c-o output.out

will appear similar to the undeference to "n" error, it is not found N, because the static file isolation, you are not able to access the A.C defined static global variables, of course you use #include "A.C", it is not the same.

Above we can draw the characteristics of static global variables:

Static global variables cannot be used by other files (global variables can be);
Other files can define the same name of the variable, no conflict (naturally, because the static isolation of the file, other files using the same name of the variable, and it does not matter);


3. Static functions: To be exact, static functions work like static global variables:

// file A.C   #include <stdio.h>      void  fn ()  {      printf ("This isnon-static func in a ");  }       // file B.C   #include <stdio.h>      externvoid fn ();  // we use extern to declare the FN () of other files for the purposes of this file.      void Main ()  {      fn ();  }  

Can output normally: This is non-static func in a.
When you add a static keyword to void fn ()? Undefined reference to "FN".

So the benefits of static functions are similar to those of static global variables:
1. Static functions cannot be used by other files;
2. The function of the same name can be defined in other files, and no conflict will occur;

There are three ways to use the above, why is it accurate to say two kinds?
1. One is the modifier variable, one is the modifier function, so it is two kinds (this kind of explanation is not many).
2. Static global variables and modified static functions are the same, and are generally merged into one. (This is a more divided approach).



The Static keyword for the C + + language has two uses:
Of course, some of the above can also be used in C + +. There are two additional ways to use it:

1. Static data member: A data member used to decorate a class, the so-called "static member". This data member has a lifetime greater than the class object (entity instance). Static data members are one copy of each class, and ordinary data members are one copy of each instance, so static data members are also called class variables, and ordinary data members are called instance variables.

#include <iostream>using namespacestd; classRectangle {Private:      intM_w,m_h; Static ints_sum;  Public: Rectangle (intWinth) { This->m_w =W;  This->m_h =h; S_sum+= ( This->m_w * This-m_h); }          voidgetsum () {cout<<"sum ="<<s_sum<<Endl;      }      }; intRectangle::s_sum =0;//Initialize        intMain () {cout<<"sizeof (Rectangle) ="<<sizeof(Rectangle) <<Endl; Rectangle*rect1 =NewRectangle (3,4); Rect1-getsum (); cout<<"sizeof (RECT1) ="<<sizeof(*rect1) <<Endl; Rectangle Rect2 (2,3); Rect2.      Getsum (); cout<<"sizeof (RECT2) ="<<sizeof(RECT2) <<Endl; System ("Pause"); return 0; }  

The results are as follows:

By graph: sizeof (Rectangle) =8bytes=sizeof (m_w) +sizeof (m_h). This means that static does not occupy rectangle memory space.
So where does the static allocate memory? Yes, the global data area (static zone).
Then look at Getsum (), the first 12=3*4, the second time 18=12+2*3. As a result, static is initialized only once, regardless of the instance.

Conclusion:

For non-static data members, each class object (instance) has its own copy. Static data members are treated as members of a class, shared by all objects of that type, and static data members are allocated only once for multiple objects of that class.
Static data members are stored in the global data area. Static data members are defined when they are allocated space, so they cannot be defined in a class declaration.

That is, you do not build a memory copy of the static int s_sum for every new rectangle, it is an instance of how many rectangle you have new, because it hooks only to the class rectangle, And it doesn't matter to you every rectangle object.


2. Static member function: A member function for modifying class.
We have a slight change to the example above:

#include <iostream>using namespacestd; classRectangle {Private:      intM_w,m_h; Static ints_sum;  Public: Rectangle (intWinth) { This->m_w =W;  This->m_h =h; S_sum+= ( This->m_w * This-m_h); }          Static voidGetsum ()//Add static here{cout<<"sum ="<<s_sum<<Endl;      }      }; intRectangle::s_sum =0;//Initialize        intMain () {cout<<"sizeof (Rectangle) ="<<sizeof(Rectangle) <<Endl; Rectangle*rect1 =NewRectangle (3,4); Rect1-getsum (); cout<<"sizeof (RECT1) ="<<sizeof(*rect1) <<Endl; Rectangle Rect2 (2,3); Rect2.  Getsum (); //You can use the object name to access the function name.cout<<"sizeof (RECT2) ="<<sizeof(RECT2) <<Endl;  Rectangle::getsum (); //You can also use the class name:: Function name to accessSystem ("Pause"); return 0; }  

The above comment is visible: add static to Getsum () to make it a static member function that can be accessed using the class Name:: Function name.
So what are the characteristics of static member functions?
1. Static members can access each other, including static member functions to access static data members and access static member functions;
2. Static member functions and static data members can be accessed arbitrarily by non-static member functions;
3. Static member functions cannot access non-static member functions and non-static data members;
4. Call the static member function, which can be accessed with the member access operator (.) and (-) call a static member function for an object of a class or pointer to a class object, or you can call it with the class name:: Function name (because he belongs to the class, it is normal to call with the class name)


The first three points are actually a point: static member functions cannot access non-static (including member functions and data members), but non-static can access static, a bit dizzy? Okay, I'll give you an explanation.
Because static is a class, it does not know that you create 10 or 100 objects, so it is not in your object's function or data is not known, so it can not be called, and in turn, you create the object is clear to the class (how else you instantiate it), So you can call a class function and a class member, just as you can call static s_sum, whether getsum is static or not.

"Reprint" The use of static in C + + detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.