Static and storage area

Source: Internet
Author: User
Tags class definition function definition static class
Static

A static data type is used to create a permanent storage space for a variable. The statically variable keeps their values unchanged when invoked between functions. When used in a class, all the variables that are used in a static variable will mirror the variable.

C # and C + + are used in two ways: static in process programming and static in object-oriented programming. The former is applied to ordinary variables and functions and does not involve classes; the latter mainly describes the role of static in class.
process-oriented static 1, the static global variable before the global variable, plus the keyword static, the variable is defined as a static global variable. Let's first give an example of a static global variable, as follows:

Example 1
#include <iostream.h>
void fn ();
static int n;  Defines a static global variable
void main ()
{
	n=20;
cout<<n<<endl;
fn ();
}
VOID fn ()
{ 
	n++;
cout<<n<<endl;
}
Static global variables have the following characteristics:
The variable allocates memory in the global data area;
Uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable declared in the function body is random unless it is explicitly initialized, and the automatic variable declared outside the function body is initialized to 0);
Static global variables are visible throughout the file in which they are declared, but not outside of the file;

The general program stores the newly generated dynamic data in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables typically release space as the function exits, and static data (even static local variables within the function) is stored in the global data area. The data in the global data area does not free up space because of the exit of the function. Attentive readers may find that Example 1 in the
Static variables are allocated memory in the global data area, including the static local variables to be mentioned later. For a complete program, the distribution in memory is as follows:
code area//low address
global Data area
heap area stack area
//high address
Code will
static int n; Defining static global Variables
To
int n; Defining Global Variables
The program still works.
Indeed, defining a global variable enables you to share variables in a file, but there are also benefits to defining static global variables:
Static global variables cannot be used by other files;
A variable with the same name can be defined in other files, and no conflict occurs;
You can change the example code above to read:
Example 2//file1
#include <iostream.h>
void fn ();
static int n;  Defines a static global variable
void main ()
{n=20;
cout<<n<<endl;
fn ();
}
File2
#include <iostream.h>
extern int n;
VOID fn ()
{n++;
cout<<n<<endl;
}
When you compile and run Example 2, you will find that the code above can be compiled separately, but there are errors at run time. Try to
static int n; Defining static global Variables
To
int n; Defining Global Variables
Compile the running program again, and realize the difference between global variable and static global variable carefully.
Note: The difference between global and global static variables
1 The global variable is a global variable that is not explicitly modified with static, but the global variable is dynamic by default, the scope is the entire project, the global variable defined within a file, and in another file, the global variable can be used by the declaration of an extern global variable name.
2 The global static variable is a global variable explicitly decorated with static, the scope is the file where the variable is declared, and other files are not available using an extern declaration.
2. Static local VariablesBefore a local variable, plus the keyword static, the variable is defined as a static local variable.
Let's first give an example of a static local variable, as follows:

Example 3
#include <iostream.h>
void fn ();
void Main ()
{
	 fn ();
	fn ();
	fn ();
}
VOID fn ()
{ 
	static int n=10;
	cout<<n<<endl;
	n++;
}
Typically, a variable is defined in the body of the function that allocates stack memory to the local variable whenever the program runs to that statement. However, as the program exits the function body, the system will reclaim the stack memory and the local variables should be invalidated accordingly.
But sometimes we need to save the value of a variable between two calls. The usual idea is to define a global variable to implement. But in this way, the variable is no longer the function itself, is no longer only controlled by the function, to the maintenance of the program inconvenience.
Static local variables can just solve the problem. Static local variables are saved in the global data area, not on the stack, and the value is persisted to the next call until the next time the new value is assigned.
Static local variables have the following characteristics:
The variable allocates memory in the global data area;
A static local variable is initialized for the first time when the program executes to the declaration of the object, that is, subsequent function calls are no longer initialized;
Static local variables are typically initialized at the declaration and, if not explicitly initialized, are automatically initialized to 0 by the program;
It always resides in the global data area until the program has finished running. But its scope is a local scope, and when the function or statement block that defines it ends, its scope ends;
3. Static functionBy adding the static keyword before the return type of the function, the function is defined as a static function. A static function, unlike a normal function, can only be visible in the file in which it is declared and cannot be used by other files.
Examples of static functions:
Example 4
#include <iostream.h>
static void fn ()//declaring a static function
void Main ()
{
	fn ();
}
VOID FN ()//defines a static function
{
	 int n=10;
	cout<<n<<endl;
}
The benefits of defining static functions:
Static functions cannot be used by other files;
A function with the same name can be defined in other files, and no conflict occurs;
Object-oriented static(Static keyword in class)
1. Static data memberAdd a keyword static before the declaration of a data member within a class, which is a static data member within a class. Give an example of a static data member first.
Example 5
#include <iostream.h>
class Myclass
{public
:
	Myclass (int a,int b,int c);
	void Getsum ();
	Private:
	int a,b,c;
	The static int sum;//declares statically data members
};
int myclass::sum=0;//defines and initializes a static data member
myclass::myclass (int a,int b,int c)
{
	this->a=a;
	this->b=b;
	this->c=c;
	Sum+=a+b+c;}
	void Myclass::getsum ()
{
	cout<< "sum=" <<Sum<<endl;
}
void Main ()
{
	Myclass M (1,2,3);
	m.getsum ();
	Myclass N (4,5,6);
	n.getsum ();
	M.getsum ();
}
As you can see, static data members have the following characteristics:
For non-static data members, each class object has its own copy. Static data members are treated as members of a class. No matter how many objects of this class are defined, static data members have only one copy in the program, and access is shared by all objects of that type. In other words, static data members are common to all objects of the class. For multiple objects of the class, static data members are allocated only once in memory for all objects to share. Therefore, the value of the static data member is the same for each object, and its value can be updated;
Static data members are stored in the global data area. Static data member definitions are allocated space, so they cannot be defined in class declarations. In Example 5, the statement int myclass::sum=0 is defined as a static data member;
Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like regular data members;
Because static data members allocate memory in the global data area and are shared by all objects of this class, it is not part of a particular class object, and its scope is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class;
Static data member initialization differs from general data member initialization. The format for static data member initialization is:
< data type > < class name >::< static data member name >=< value >
Static data members of a class have two forms of access:
< class object name >.< static data member name > or < class type name >::< static data member name >
If the access permission of a static data member is allowed (that is, a member of public), the static data member can be referenced in the program in the format described above;
Static data members are primarily used when each object has the same attribute. For example, for a deposit class, the interest for each instance is the same. Therefore, interest should be set as a static data member of the deposit class. There are two benefits, first, that the interest data members share the memory allocated in the global data area, regardless of the number of deposit objects defined, thus saving storage space. Second, once the interest needs to change, as long as the change, then all the deposit of the object of interest all change over;
There are two advantages to using static data members compared to global variables:
Static data members have no access to the global namespace of the program, so there is no possibility of conflict with other global names in the program;
can realize information hiding. Static data members can be private members, and global variables cannot;
#include <iostream>
using namespace std;
Class P
{public
:
	P (): A (0) {};
	P (int i): A (i) {};
	void setstatic (int i)
	{
		sa = i;
	}
	void Printmem ()
	{
		cout<< "sa=" <<sa<< "\ta=" <<a<<endl;
	}
Private:
	int A;
	static int sa;
int p::sa = ten;
int main ()
{
	P A;
    P B (2);
	A.printmem ();
	A.setstatic (5);
	B.printmem ();
   return 0;
}
Run Result:
sa=10   a=0
sa=5    a=2
2. Static member functionAs with static data members, we can also create a static member function that serves all of the class's services rather than the specific object of a particular class. Static member functions, like static data members, are internal implementations of a class and are part of the class definition. Ordinary member functions implicitly imply a this pointer, the this pointer points to the object itself of the class, because the ordinary member function is always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS-&GT;FN (). However, a static member function does not have the this pointer because it is not associated with any object, as opposed to a normal function. In this sense, it does not have access to non-static data members belonging to the class object, nor does it have access to non-static member functions, and it can only invoke the rest of the static member functions. Here's an example of a static member function.
Example 6
#include <iostream.h>
class Myclass
{public
:
	Myclass (int a,int b,int c);
	static void Getsum ();/declaring a statically member function
private:
	int a,b,c;
	The static int sum;//declares statically data members
};
int myclass::sum=0;//defines and initializes a static data member
myclass::myclass (int a,int b,int c)
{ 
	this->a=a;
	this->b=b;
	this->c=c;
	Sum+=a+b+c; Non-static member functions can access static data member
}
void Myclass::getsum ()///static member function implementation
{/
	/cout<<a<<endl;// Error code, a non-static data member
	cout<< "sum=" <<Sum<<endl;
}
void Main ()
{
	Myclass M (1,2,3);
	m.getsum ();
	Myclass N (4,5,6);
	n.getsum ();
	Myclass::getsum ();
}
For static member functions, you can summarize the following points:
A function definition that appears outside the class body cannot specify a keyword static;
Static members can access each other, including static member functions accessing static data members and accessing static member functions;
Non-static member functions can access static member functions and static data members arbitrarily;
Static member functions do not have access to non-static member functions and non-static data members;
Because there is no extra overhead for this pointer, static member functions have a slight increase in speed compared to the global functions of a class;
Calling static member functions, you can call static member functions with member access operators (.) and (->;) for objects of a class or pointers to class objects, or you can use the following format directly:
< class name >::< static member function name > (< parameter table >)
Calls a static member function of a class.
Role
Static statically variable declaration character. In declaring its program block, subroutine block or function inside valid, value hold, allocate memory space throughout program, compiler default value 0.
is a commonly used modifier in C + +, which is used to control how variables are stored and visible.
Why to introduce static
A variable that is defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, as you know, the space the function allocates on the stack is released at the end of the function execution, which creates a problem: How to save the value of this variable in the function to the next call. The easiest way to think about it is to define a global variable, but there are many drawbacks to defining it as a global variable, the most obvious disadvantage being that it destroys the scope of the variable's access (so that the variables defined in this function are not just controlled by this function).
When do you use static
A data object is required to serve an entire class rather than an object, while trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.
The internal mechanism of static
Static data members must exist when the program starts running. Because a function is invoked in the program's run, static data members cannot allocate space and initialize within any function.
In this way, it has a space allocation of three possible places, one is the header file of the outer interface of the class, where there are class declarations, and the internal implementation of the class definition, where the member function of the class is defined, and the third is the global data declaration and definition at the front of the application's main () function.
Static data members cannot be defined in the declaration of a class (only data members can be declared) in order to physically allocate space. A class declaration declares only the "Dimensions and Specifications" of a class and does not carry out actual memory allocations, so it is wrong to write a definition in a class declaration. It also cannot be defined as an external definition of a class declaration in a header file, because that would result in multiple definitions of it in a source file that uses the class.
Static is introduced to tell the compiler to store variables in the static store of the program rather than on the stack, static
Data members are initialized sequentially in the order in which they appear, and note that when static members are nested, the nested members are initialized. The order of elimination is the inverse order of initialization.
The advantages of static
Memory can be saved because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to share. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, ensuring that all objects access the updated value of the same, this can improve time efficiency.
Apply formatting
When referencing static data members, the following format is used:
< class name >::< static member name >
If the access permission of a static data member is allowed (that is, a member of public), you can refer to the static data member in the program in the format described above.
Attention matters
The static member function of the ⑴ class is an object that belongs to the entire class rather than the class, so it does not have the this pointer, which causes it to access only static data and static member functions of the class.
⑵ cannot define a static member function as a virtual function.
⑶ because the static member is declared in the class, the operation is outside, so the address operation is somewhat special, the variable address is a pointer to its data type, and the function address type is a "nonmember function pointer".
⑷ because static member functions do not have the this pointer, they are almost equivalent to the nonmember function, resulting in an unexpected benefit: to become a callback function that allows us to combine C + + and c-based X window systems, It is also successfully applied to the thread function.
⑸static does not increase the time and space overhead of the program, but she also shortens the access times of subclasses to static members of the parent class, saving the memory space of the child classes.
⑹ static data members precede the <; definition or description >; by adding a keyword static.
⑺ static data members are stored statically, so it must be initialized.
⑻ static member initialization differs from general data member initialization:
Initialization is done outside the class body, without the preceding static, so as not to be confused with a general static variable or object;
The private,public of the access rights control character of the member is not added when initializing;
The scope operator is used when initializing to indicate the class to which it belongs;
So we get the format of the static data member initialization:
<; data type ><; class name >::<; static data member name >=<; value >
⑼ in order to prevent the parent class from being affected, you can define a subclass with the same static variable as the parent class to mask the effects of the parent class. Here's one thing to note: we say that static members are shared by the parent class and subclass, but we have the duplicate definition of static members, and this will not cause errors. No, our compiler uses a neat trick: name-mangling to generate a unique flag. The test questions that often appear in the written interview of each communication company are static functions and function.


Storage AreaIn C and C + +, there are three basic ways to use the storage area:
1 Static storage area (Memory)
In a static store, a connector (linker) Allocates space for an object based on the requirements of the program. Global variables, static class members, and static variables in functions are assigned to the zone. An object allocated in the zone is only constructed once, and its lifetime is maintained until the end of the program. The address is fixed at the time the program is running. In programs that use threads (thread, shared address space concurrency), static objects can cause problems because static objects are shared and locking is required for normal access.
2) automatic storage area (Automatic Memory)
The parameters and local variables of the function are assigned here. Each call to the same function or block has its own separate location within the region. This storage is automatically created and destroyed, and is therefore called an automatic store. Automatic storage is also referred to as "on the stack".
3 Free Storage Area
In this area, the program must explicitly request space for the object, and can release the requested space (using the new and delete operators) after the use is complete. When a program needs more space, it uses new to apply to the operating system. In general, a free store (also known as a dynamic store or heap (heap)) grows during the lifetime of a program, because the space that is occupied by other programs is never returned to the operating system.
Heap and Stack are a partition of memory area respectively!
Generally divided into 5 areas, namely the heap, stack, free storage area, global/static area and constant storage area.
Stack-----is the storage area of variables that are allocated by the compiler when needed and automatically understood when they are not needed. The variables inside are usually local variables, function parameters, and so on.
Heap-----is the memory blocks that are allocated by new, their release compiler is not managed by our application to control, generally a new will correspond to a delete. If the programmer is not released, the operating system will automatically recycle after the program finishes.
The Free store-----is the memory block that is allocated by malloc, which is very similar to the heap, but it ends its own life with freedom.
Global/Static storage-----Global variables and static variables are assigned to the same memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C + + without this distinction, they share the same memory area.
Constant Store-----This is a special storage area where constants are stored and are not allowed to be modified
Reference:
http://blog.csdn.net/zhaozh2000/article/details/6293294
Http://zhidao.baidu.com/question/169199478.html
Http://www.cnblogs.com/nkxyf/archive/2012/03/14/2382637.html

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.