Some concepts in C ++ and their differences (need to be deeply understood ):
(1) local variable global variable static variable const constant register variable macro defined constant static variable
(Note: including their memory allocation, scope, initialization, etc)
Local variable: The variable scope defined in the function (process) is the Function Memory Allocation that defines the variable: Address Allocation in the stack from high to low ;.
Global variables: usually defined at the beginning of the file (ideal location ), when these functions and some functions in other source program files in the same program need to use the global variable, use extern inside the function to indicate that the variable is external; scope: it remains valid during program execution. Initialization: If Initialization is not performed during definition, the system automatically assigns a value to 0 for memory allocation: allocated from the static storage area.
Static variables: You can declare variables as static variables using static statements. The scope is the current subroutine module, and its lifetime is the end of the entire program. Memory Allocation: global/static storage area;
Register Type: The purpose of using the keyword register to declare the register type is to put the declared variables into the register, so as to speed up program operation.
Question 8: Tell me as many static and const keywords as possible
Answer:
The static keyword has at least N functions:
(1) The static variable in the function body applies to this function body. Unlike the auto variable, the memory of this variable is allocated only once, therefore, the value remains the value of the previous time during the next call;
(2) The static global variables in the module can be accessed by the functions used in the module, but cannot be accessed by other functions outside the module;
(3) The static function in the module can only be called by other functions in the module. The scope of use of this function is limited to the module that declares it;
(4) static member variables in the class belong to the entire class and only one copy of all objects in the class;
(5) The static member function in the class belongs to the whole class. This function does not receive the this pointer, so it can only be a static member variable of the category.
The const keyword has at least N functions:
(1) to prevent a variable from being changed, you can use the const keyword. When defining the const variable, you usually need to initialize it, because there will be no chance to change it in the future;
(2) For pointers, you can specify the pointer itself as const, or you can specify the data referred to by the pointer As const, or both of them as const;
(3) In a function declaration, const can modify the form parameter, indicating that it is an input parameter and cannot change its value within the function;
(4) If the member function of the class is specified as the const type, it indicates that it is a constant function and the member variables of the class cannot be modified;
(5) For a member function of the class, you must specify its return value as the const type so that its return value is not the "Left value ". Example: const classa operator * (const classa & A1, const classa & A2 );
The return result of operator * must be a const object. If not, such abnormal code will not cause compilation errors: classa A, B, C;
(A * B) = C; // assign a value to the result of a * B
Operation (A * B) = C obviously does not conform to the programmer's original intention, and does not make any sense.
Analysis:
Surprised? What are the functions of small static and const? If you can only answer 1 ~ 2. You have to close the door and practice well.
(2) differences between malloc/New and free/delete
Malloc, free is the standard function library of C language, and new/delete is the c ++ operator, they can dynamically apply for memory and release the memory;
For non-Internal data objects, the use of malloc/free alone cannot meet the needs of dynamic objects. the constructor must be automatically executed when the object is to be created. The Destructor must be executed before the object is extinct. Because malloc/free is not an operator, it is not controlled by the compiler, you cannot impose constructor and destructor tasks on malloc/free. therefore, the C ++ language requires a new operator for dynamic memory allocation and initialization, and a delete operator for memory cleanup and release.
We should not attempt to use malloc/free to manage the memory of dynamic objects. We should use new/Delete. Because the internal data type "object" does not have a process of construction and analysis, malloc/free and new/delete are equivalent to them.
Since the new/delete function completely covers malloc/free, why does C ++ not eliminate malloc/free? This is because C ++ programs often call C functions, and C Programs can only use malloc/free to manage dynamic memory.
Another advantage of the malloc/free function is that it can be used in combination with realloc, which may not necessarily lead to memory movement when the memory block needs to be expanded; when new/delete is used, only the new []-copy-Delete [] operation sequence can be used to complete the operation, causing memory Movement each time.
(3) What are the advantages of macro definitions of inline functions.
C ++ supports inline functions to improve the efficiency of function execution.
Inline functions directly insert code outside of the call, which reduces the resource consumption of common functions and checks the parameter type. macros are not functions, it only replaces the strings in the program with the macro before compilation (before pre-compilation), saving the process of parameter pressure stacks, generating call calls for the assembly language, returning parameters, and executing return,Parameter types are not checked;
Both of them can improve the running efficiency, but the biggest drawback of using macro code is error-prone. For C ++, using macro code has another drawback: unable to operate private data members of the class; the function inline mechanism in the C ++ language provides both macro code efficiency and security, and allows you to operate data members of the class freely. Therefore, in C ++ programs, we should replace all macro code with inline functions. I am afraid assert is the only exception.
(4) What are the memory allocation methods? Why? What is the difference? What is the impact on Compilation speed?
There are three methods for memory allocation:
From the static storage region allocation, it is allocated when the internal program is compiled, and the internal program exists throughout the runtime, such as global variables and static variables.
Stack allocation. For example, function local variables can be allocated on the stack. The function is released at the end of the function. The stack memory allocation computation is built into the processor's instruction set, which is highly efficient, the memory allocation is continuous, and the stack is a data structure extended to the low address, but the capacity is limited;
Allocate resources from the stack, that is, dynamic memory allocation. New/malloc is used when the program is running, and the programmer is responsible for the delete/free release. If the programmer is not released, at the end of the program, it may be recycled by the operating system. similar to a linked list, the distribution in the memory is not consecutive. They are linked by pointers of memory blocks in different regions. once a node is disconnected from the chain, we need to release the disconnected node from the memory. the lifetime of the dynamic memory is determined by us and flexible to use (the heap is a data structure extended to the high address and is a discontinuous memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system), but there are many problems.
Comparison of application efficiency:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.
(5) What is polymorphisn )? For example, try
Literally, it means "multiple shapes ". Reference Charlie Calverts's description of polymorphism-polymorphism is a technology that allows you to set a parent object to be equal to one or more of its sub-objects, the parent object can operate in different ways based on the features assigned to its sub-objects (from "delphi4 Programming Technology insider "). To put it simply, you can assign a pointer of the subclass type to a pointer of the parent class. Polymorphism is implemented by virtual functions in Object Pascal and C ++.
Polymorphism is a technique that allows the parent object to be set to be equal to one or more of its sub-objects, such as parent: = Child; after being assigned a value, the parent object can operate in different ways based on the features assigned to its sub-objects. That is to say, a father acts like a son, rather than a father.
To put it simply, to create a parent class variable, its content can be the parent class or its sub-class. When the sub-class has the same function as the parent class, when this variable is used to call this function, the class that defines this variable, that is, the parent class, will be called for the function with the same name, when the virtual keyword is added before the function in the parent class, the function with the same name of the subclass will be called.
Class {
Public:
A (){}
Virtual void Foo (){
Cout <"This Is A." <Endl;
}
};
Class B: Public {
Public:
B (){}
Void Foo (){
Cout <"This is B." <Endl;
}
};
Int main (INT argc, char * argv []) {
A * A = new B ();
A-> Foo ();
Return 0;
}
This will show:
This is B.
If the virtual is removed, the following information is displayed:
This is.
(6) What is the difference between struct and class? Is struct in C language the same as struct in C ++? What is the difference?
(1) permissions are inherited by default. If it is not explicitly specified, the inheritance from class is handled by private inheritance, and the inheritance from struct is handled by Publ IC inheritance;
(2) default access permissions of members. By default, class members are private and struct members are public by default.
If there is no polymorphism or virtual inheritance, in C ++, the access efficiency of struct and class is the same! Simply put, the efficiency of accessing the data member and non-virtual functions of the class is exactly the same as that of struct! Whether the data member is defined in the base class or a derived class.
(7) What is a wild pointer? When does a wild pointer appear? (No initialization. No value is null after Delete)
The wild pointer is not a null pointer, It is a pointer to the junk memory, that is, a pointer to the memory that is unavailable. Generally, operations on this pointer will produce unknown errors, generally, the NULL pointer is not used, but the NULL pointer is very dangerous. If does not work for it. There are two possible causes: No initialization and no value assignment for delete/free is null.
(8) Are you familiar with precompiled commands? What is Conditional compilation used? Will you write?
The pre-processing process scans the source code and performs initial conversion to generate new source code for the compiler. It can be seen that the preprocessing process processes the source code prior to the compiler.
The following are some pre-processing commands:
Command usage
# Empty command, no effect
# Include contains a source code file
# Define definition macro
# UNDEF cancel a defined macro
# If the given condition is true, compile the following code
# Ifdef if the macro has been defined, compile the following code
# Ifndef if the macro is not defined, compile the following code
# Elif if the previous # if given condition is not true and the current condition is true, compile the following code:
# Endif end one. # If ...... # Else Conditional compilation Block
# Error stops compilation and displays error information
The Conditional compilation command determines which codes are compiled and which ones are not compiled. You can determine the compilation conditions based on the expression value or whether a specific macro is defined.
For example:
To prevent header files that can only be contained once from being contained multiple times, you can use compile-time conditions to control the header files. For example:
/* My. H */
# Ifndef my_h
# Define my_h
......
# Endif
1. # If command
# The if command detects the constant expression following the creation of another keyword. If the expression is true, the code after compilation will be known until # else, # Elif or # endif appears; otherwise, the compilation will not be performed.
2. # endif command
# Endif is used to terminate # If preprocessing command.
# Define debug 0
Main ()
{
# If debug
Printf ("debugging \ n ");
# Endif
Printf ("running \ n ");
}
Because the debug macro defined by the program represents 0, the # If condition is false, and the subsequent code is not compiled until # endif, so the program directly outputs the running.
If the # define statement is removed, the effect is the same.