C ++ Primer study note _ 23 _ class and data abstraction (9) -- four object lifetime and scope, static usage summary, primer_23

Source: Internet
Author: User

C ++ Primer study note _ 23 _ class and data abstraction (9) -- four object lifetime and scope, static usage summary, primer_23

C ++ Primer study note _ 23 _ class and data abstraction (9) -- four object lifetime and scope, static usage Summary

Preface:


The memory occupied by the program is divided into the following parts.

(1) stack)

Stores the function parameter values and local variable values. The memory allocation is continuous. The stack content only exists within the function range. When the function stops running, the content will be automatically destroyed, which features high efficiency but limited space.

Note: Usually the stack space is relatively small, usually 1 MB ~ 2 MB, so it is not suitable for allocating large objects in the stack.

(2) heap)

Memory dynamically allocated by malloc functions or new operators. its lifecycle is determined by free or delete. Similar to a linked list, the distribution in the memory is not consecutive. They are linked by memory blocks in different regions through pointers. It exists until the end of the program until it is released. It is characterized by flexible use, large space, but error-prone.

(3) static zone (Global Zone) (static)

Save automatic global variables and static variables (including static global and local variables ). The content in the static zone exists in the life cycle of the total program, which is allocated by the compiler during compilation and released by the system after the program ends.

(4) text Constant Area

Constant strings are placed here. The program is released by the System

(5) program code area

Stores the binary code of the function body.



1. Four types of object survival and scope

(1) stack object

Implicit call of Constructor (no explicit call in the Program)

(2) Heap object

Implicit call of Constructors (no explicit call in the program) must be explicitly released

(3) Global Object and static Global Object

The global object is constructed prior to the main function.

Initialized global variables or static global objects are stored in the. data Segment.

Uninitialized global variables or static global objects are stored in. bss segments.

(4) Static local object

Initialized static local variables are stored in the. data Segment.

Uninitialized static local variables are stored in the. bss segment.

Note: The direction of the arrow indicates that the stack is extended from high address to low address, and the stack is extended from low address to high address.

[Example]
# Include <iostream> using namespace std; class Test {public: Test (int n): n _ (n) {cout <"Test" <n _ <"... "<endl ;}~ Test () {cout <"~ Test "<n _ <"... "<endl;} private: int n _;}; int n; // uninitialized global variable. The initial value is 0. N is stored in the. bss segment. (Block started by symbol) int n2 = 100; // initialized global variable. The initial value is 100. N2 is stored in the. data Segment. Test g (100); // The Global object is constructed before the main function static Test g2 (200); int main (void) {cout <"Entering main... "<endl; Test t (10); // The objects created on the stack are automatically released at the end of the lifetime {Test t (20 );} {Test * t3 = new Test (30); // delete t3;} {static int n3; // N3. static int n4 = 100 in the bss segment (initialized during compilation); // n4 is stored in. static Test t4 (333) in the data Segment (during compilation); // class at runtime of the t4 object. data Segment} cout <"Exiting main... "<endl ;}
Running result:
Test 100...
Test 200...
Entering main...
Test 10...
Test 20...
~ Test 20...
Test 30...
~ Test 30...
Test 333...
Exiting main...
~ Test 10...
~ Test 333...
~ Test 200...
~ Test 100...


Ii. Summary of static usage

(1) It is used to modify the variable inside the function, that is, the static variable in the function. The lifetime of this variable is longer than that of this function, so that the function has a certain "State ". Functions that use static variables are generally not reentrant, nor thread-safe, such as strtok (3 ).
(2) When modifying a variable or function at the file level (outside the function body), it means that the variable or function is only visible in this file, and the variable or function cannot be accessed in other files.
The use of the C language is clear and generally not confusing.


Because C ++ introduces classes, while maintaining compatibility with C, the static keyword has two new usage methods:
(3). It is used to modify the data members of a class, that is, "static members ". This type of data member has a lifetime greater than the class Object (instance/instance ). A static data member has one copy for each class, and a common data member has one copy for each instance.
(4). It is used to modify the member functions of the class, that is, the so-called "static member functions ". This type of member function can only access static members and other static member functions, but cannot access non-static members and non-static member functions.


1. Three Methods of static in the program

(1) static is visible only to the current file in the function or globally.

(2) static only belongs to one class, not a specific object, or the variables and functions of the object.

(3) statci only applies to the c/cpp file that defines the header file in the header file. Other files with the same header file are invisible. (If you see a Statement on the Internet, it is not necessarily true. This definition is harmful: If the header file contains multiple times, variables are defined several times, which is easy to be repeated, therefore, it is not recommended to define static in the header file .)


2. Ignore the functions of class and static

(1) first role: Hide

When we compile multiple files at the same time, all global variables and functions without the static prefix are globally visible. For example, Compile two source files, a. cpp and main. cpp. The content of a. cpp is as follows:

#include <iostream>using namespace std;char a = 'A';void msg(){        cout << "Hello World" << endl;}
The global variables a and msg defined in a. cpp can be used in main. cpp, extern.

However, if static is added, other source files are hidden. For example, if static is added before the definitions of a and msg, main. cpp will not be able to see them.

[Example]

In a cpp file, a static global variable is defined. Which of the following statements is true ()

A. The variable can only be used in the compilation module where the cpp is located.

B. The value of this variable cannot be changed.

C. The variable cannot be referenced in the member functions of the class.

D. This variable can only be of the basic type (such as int and char) and cannot be of the C ++ type.

Answer:


For functions, the role of static is limited to hiding, and for variables, satic has the following two functions.

(2) The second function is to initialize 0 by default.

Including uninitialized Global static variables and local static variables. In fact, uninitialized global variables also have this attribute. Because uninitialized global variables and uninitialized static variables are stored in BSS segments in the same region. In the BSS segment, the default values of all bytes in the memory are 0x00.

[Example]

What are the following output values?

#include <iostream>#include <string>using namespace std;string str1;static int a;int b[2];int main(){    string str2;    int c;    int d[2];        cout << str1 << endl;    cout << str2 << endl;    cout << a << endl;    cout << b[0] << " " << b[1] << endl;    cout << c << endl;    cout << d[0] << " " << d[1] << endl;    return 0;}

Answer: str1 and str2 are of the string type. The default constructor of string is automatically called to initialize each element as an empty string. a is a global variable and 0 is initialized. B is a global array, each element is initialized to 0, c is a local variable, and its value is a junk value; d is a local array, and the value of each element is also a junk value.


(3) third role: to maintain the persistence of local variable content

Local variables in the function exist when called and disappear when you exit the function. However, although static local variables are defined in the function, static local variables always exist, that is to say, its lifetime is the entire source program. It is characterized by only one initialization and "Memory".

Although the lifetime of the static local variable is the entire source program, its scope is still the same as that of the local variable. That is, the variable can only be used by the function defining the variable. After exiting the function, although the variable still exists, it cannot be used, and the variable can be redefined outside the scope.


[Example 1]

A local variable defined by static is used in a function. The variable is initialized only once and has "Memory". )

Answer: Correct.


[Example 2]

Which of the following statements is true? () (multiple choice)

A. static global variables can only be used in defined files. Common global variables can be used in all files.

B. static local variables are stored in the bss segment or data segment, so that the previous value can be assigned. Common local variables are in the stack and cannot be assigned with the previous value.

C. static functions can only be used in the current source file. Common functions can be used in other files.

D. If the static variable is not initialized, its value is undefined.

Answer: ABC. In B, the initialized static variables are stored in the data segment, and uninitialized static variables are stored in another adjacent area (BSS segment.


[Example 3]

Which of the following statements about static variables is true? () (multiple choice)

A. Static local variables are allocated in the static storage area.

B. Static external variables can be assigned with or without an initial value.

C. Static external variables act the same way as external variables

D. The static local variable remains its value at the end of the function call and will not disappear

E. Only one initial value is assigned to the static local variable.

Answer: ABDE. In C, if the scope of static local variables is the same as that of local variables, it is correct. Pay attention to the problem deformation.


[Example 4]

void fun(){    static int val;    ......}

In the preceding example, the memory address of the variable val is located in ().

A. initialized data segments

B. uninitialized data segments

C. Heap

D. Stack

Answer: B. The data segment is not initialized, that is, the BBS segment. If the data segment is initialized, the data segment is initialized.


3. Role of static in the class

C ++ reuses the static keyword and gives it a different meaning: It indicates variables and functions belonging to a class rather than any specific object of this class.

(1) static data member

Static data members exist independently of any objects of the class. That is to say, when an instance of a class modifies the static data member variable, the modified value is also seen by all other instances of the class.

Static data members follow the public, protected, and private access rules like common data members.

Static data members are also stored in the global (static) storage area. Space must be allocated when defining static data members, so they cannot be defined in the class declaration. Static data members must be defined externally (exactly once) in the class definition body ).

[Example 1]

Which of the following statements about static data members is true ()

A. static data members can be initialized in the class body.

B. static data members cannot be called by class objects

C. static data members are not subject to private control characters

D. static data members can be called directly by class names.

Answer: D. It can be called by class object or by class name.


[Example 2]

Which of the following statements about the memory distribution of object members in C ++ is true ()

A. No matter how many objects are generated by this class, static member variables always have only one instance and exist without an object instance.

B. the sorting order of non-static member data in the class will be the same as the declared order. Any static member involved in the middle will not be put into the memory layout of the object.

C. In the same access segment (that is, private, public, protected, and other segments), the data members are arranged in line with the "Later-appearing members have a higher memory address in the object"

D. The memory occupied by class objects with virtual functions is proportional to the number of virtual functions.

Answer: ABC.

The layout of data members in the class is as follows:

-- The class objects of non-static members are arranged in the same order as the declared order. Any static members declared in the middle of the class objects are not placed in the object layout.

-- Static data members are stored in the global (static) area of the program and are irrelevant to individual class objects.

In the C ++ standard, in the same access block, that is, private, public, and protected segments, the arrangement of members only requires that the later member has a higher address in the class object. That is to say, it is not necessarily sequential. What is between the declared members? For example, some bytes that need to be filled when the boundaries of members are adjusted.


(2) static member functions

Compared with common member functions, static member functions do not have the this pointer because they are not associated with any objects. Therefore, it cannot access non-static data members of class objects or non-static member functions. It can only call other static member functions and access static data members.

Because the static member is not part of any object, the static member function cannot be declared as const.

Finally, static member functions cannot be declared as virtual functions or volatile.

class base{    virtual static void fun1();  //Error    static void fun2() const;  //Error    static void fun3() volatile;  //Error};

Static member functions can be summarized as follows:

First, static members can access each other, including static member functions accessing static data members and static member functions. Static member functions cannot access non-static member functions and non-static data members. Non-static data members can access static member functions and static data members at will.

Second, because there is no additional overhead of this pointer, static member functions will increase slightly compared with non-static member functions of the class.


[Example]

Which of the following statements about static members of a class is false ()

A. Objects of this class share the value of their static member variables.

B. static member variables can be accessed by all methods of the class.

C. The static method of this class can only access static members of this class.

D. The value of the static data member variable of this class cannot be modified.

Answer: D.


(3) using static member variables instead of global variables has three advantages:

First, the static member name is in the scope of the class, so it can avoid conflicts with other class members or global object names.

Second, encapsulation can be implemented. Static members can be private members, but global objects cannot.

Third, it is easy to see through the reading program that static members are associated with specific classes. This visibility clearly shows the programmer's intent.



Refer:

C ++ primer version 4
Valid tive C ++ 3rd
Http://blog.csdn.net/jnu_simba/article/details/9237581

Http://blog.csdn.net/zjf280441589/article/details/24730905
C ++ programming specifications


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.