The basic grammar

1, static keyword function

1. Global static variables Global variables with the static keyword can only be used in this file. Stored in static storage, it exists for the entire duration of the program. 2. Local static variable scope is still local scope. Once out of scope, however, it is not destroyed, but stored in the program and cannot be accessed until the function is called again. Static functions can only be used in the file in which they are declared, they cannot be used in other files, and they do not conflict with other CPP functions of the same name. Static members can be used to share data between multiple objects without breaking the hiding principle. Static data members are stored in one place and shared by all objects. Static functions of a class belong to static members of the class. References to static members do not require object names. Note that the implementation of a static member function cannot refer directly to a non-static member of the class; it can refer directly to a static member of the class.

2, C++ four cast conversion

Static_cast: used for various implicit conversions, polymorphic up conversions, and unsafe down conversions. Dynamic_cast: used for dynamic type conversions, used for up and down conversions between class hierarchies. Only Pointers or references can be rotated. For Pointers, nullptr is returned on conversion failure, and for references, an exception is thrown on conversion failure. Reinterpret_cast: Almost all interpret_casts may cause problems. C casts cannot be error-checked.

3. Pointers and references

1, Pointers have their own space, a reference is an alias, sizeof pointer for 2 and 4, the size of the object reference is cited 3, Pointers can be initialized to NULL, the reference is initialized must be an existing object reference 4, pointer can point to other objects, reference is only an object reference, can not be changed 5, Pointers can multistage, 6. Return an object with dynamic memory allocation, using a pointer.

4. Smart Pointers

Effect: The requested space is forgotten at the end of the function, causing a memory leak. A smart pointer is a class that, when out of scope, automatically calls the destructor, which automatically frees resources so that there is no need to manually free memory. Unique_ptr: Ensures that only one smart pointer points to the object at the same time. Shared_ptr: Multiple smart Pointers can point to the same object, and the object and associated resources are released when the last reference is destroyed. Its member function use_count() is used to check the number of resource owners. Call release, the current pointer releases resource ownership, and the count is reduced by one. Weak_ptr: Does not control the object life cycle, it points to a shared_PTR managed object. Shared_ptr is used to manage the object’s memory. Weak_ptr only provides a means of access to the managed object. The construction and destruction of weak_ptr do not cause an increase or decrease in the count. It is used to solve the deadlock problem when shared_ptr references each other: if two shared_ptr references each other, the reference count of the two Pointers can never fall to zero and the resource is never freed. Example: a Woman is referenced inside the Man class, and a Man is referenced inside the Woman class. When a man and a woman are married, they directly have a cross-reference problem. There is a shared_ptr variable inside man that manages the lifetime of wife, meaning that wife must have passed away after husband. Similarly, there is a shared_ptr variable inside woman that manages the lifetime of husband, meaning husband must die after wife. This is the problem with circular references: husband’s life is determined by wife’s life, wife’s life is determined by husband’s life, and neither of them dies, violating the laws of nature and causing a memory leak. Blog.csdn.net/shanno/arti…

Arrays and Pointers

6. Wild Pointers

A wild pointer is a pointer to a deleted object or an area of memory that has not been requested for access

7. How to solve the memory leak of smart pointer

Memory leaks of smart Pointers are mainly caused by circular references. A Weak_ptr pointer can be introduced. Weak_ptr’s constructor does not modify the value of the reference count, so it does not manage the object’s memory. It is like a normal pointer, but does not point to the shared memory of the reference count. Weak_ptr can detect if the managed object is released, thus avoiding illegal access.

Destructors must be virtual

If the parent’s destructor is not virtual, then when we new a subclass object and point to it with a pointer to the base class, only the base object is freed and the space of the subclass object is not freed, resulting in a memory leak.

The default destructor in C++ is not a virtual function because the virtual function requires extra virtual table and pointer to the virtual table, occupying extra memory. If the class is not inherited, making the destructor virtual is a waste of memory.

Function pointer

A function pointer is a pointer variable to a function. C At compile time, each function has an entry address, which is the address to which the function pointer points. Once you have a pointer variable to a function, you can call the function with that pointer. Purpose: call function and make function parameters, such as callback function

Destructor function

The difference between static function and virtual function

Static functions are defined at compile time, while virtual functions are dynamically bound at run time. Virtual functions are called with a memory overhead because of the virtual function table mechanism.

Overloading and overwriting

Overloading: two functions with the same name but different overridden argument columns: subclass inherits the parent class. The function in the parent class is virtual. Redefine the virtual function in the subclass.

Virtual functions and understanding of polymorphism

Polymorphism is classified as static and dynamic. Static polymorphism is determined at compile time by overloading. Dynamic polymorphism is implemented using the virtual function mechanism and is dynamically bound at run time. For example, if a pointer to a superclass type points to a subclass object, the function overwritten by the subclass is called when the superclass pointer is used to call a virtual function in the subclass.

Const decorates a member function

Indicates that the function call does not make any changes to the object. If you are sure that no changes will be made to the object, you should qualify the function as const.

Implicit type conversion

For built-in types, an implicit type conversion occurs when a variable of low precision is assigned to a variable of high precision.

16, virtual function implementation

In a class with virtual functions, the class begins with a pointer to the virtual table. This pointer points to a virtual table with the address of the virtual function in the table. The actual virtual function is in the code segment (.text). When a subclass overrides a virtual function in the parent class, it replaces the address of the inherited virtual table with the address of the rewritten function. Virtual functions are used to increase the access memory overhead and reduce efficiency.

17. How do we define constants in C++? Where constants are stored in memory

Constant definitions must be initialized. For local objects, constants are stored in the stack area, and for global objects, constants are stored in global/static storage. Du yu literal constants, constants stored in the constant store.

18. Auto, NULlPTR keyword

Auto keyword: The compiler can automatically deduce the type from the initial value. However, it cannot be used for function parameter passing or array type derivation. Nullptr keyword: NULlptr is a special type of literal that can be converted to any other pointer type. NULL, which is generally defined as 0 by macros, can be problematic when overloaded. Smart pointer: STD ::shared_ptr, STD ::weak_ptr and other types of smart pointer are added in C++11 to solve the problem of memory management. Initializer list: Initializer lists are used to initialize classes. Rvalue reference: Rvalue reference can realize mobile semantics and perfect forwarding, eliminate unnecessary object copy when two objects interact, save operation storage resources and improve efficiency.

20, right value

In C++, an lvalue is usually an addressable value, and a named value is an lvalue, while an unnamed value is an rvalue. In reference C++11, an rvalue consists of two concepts, a decrement and a pure rvalue. Pure rvalues are used to identify temporary variables. An rvalue reference is a type that references an rvalue. More detailed differences can be found in this note: blog.csdn.net/qq_42604176…

21. Lambda expressions

Lambda is an anonymous function, and you can think of a Lambda expression as a piece of code that can be passed (passing code like data). You can write cleaner, more flexible code. For example, if you have some small functions in your code that are called only once (such as function Pointers), you can use lambda expressions instead to make the code look simpler and easier to use. For details and understanding, see here: where Lambda expressions are used

The container

STL iterator delete element iterator invalid

Erase invalidates iterators for each successive element, but moves each element forward one position and returns the next valid iterator.

Erase invalidates the iterator of the current element, but because of its internal structure, deleting the current element does not affect the iterator of the next element. We simply record the iterator of an element before we call erase.

3. For list, it uses a discontinuous allocation of memory and erase returns the next valid iterator, so both methods can be used

2. What does STL consist of

Container, iterator, functor, algorithm, allocator, container adapter

The allocator allocates storage space to the container, the algorithm retrieves the contents of the container through iterators, the functor assists the algorithm in the operation, and the adapter ADAPTS the functor.

3. Vector is different from list

Vector A container of contiguous storage; a dynamic array that allocates space on pairs.

Underlying implementation: array

Double capacity growth:

When we add an element to the vector, we add it to the last position, and then adjust the iterator.

If there is no remaining space, it will reconfigure the space twice the original number of elements, and then initialize the new space by copying the original space elements, and then add elements to the new space. Finally, the original space will be destructed and the previous iterator will become invalid. List Bottom layer: bidirectional linked list

4. The function of iterators in STL. Why iterators when there are Pointers

The underlying

1. C/C++ memory distribution

Virtual memory is divided into code segment, data segment, BSS segment, heap area, file mapping area, stack area. Code snippet: read-only storage area, text area. BSS section: Store global and static variables that have been initialized in the program. Heap area: Programmer dynamically allocates memory, and programmer manually releases mapping area: Store dynamic link library and call mmap function for file mapping stack: store function return address, parameters, local variables, return value

2. Underlying principles of MALloc

Malloc uses the method of memory pooling. It allocates a large chunk of memory for the heap and then divides the heap into many memory blocks. The blocks are used as the basic unit of memory management. When a user requests memory, an appropriate free block is allocated directly from the heap. Malloc uses implicit linked lists to separate the heap into contiguous chunks of variously sized memory. All memory blocks are managed simultaneously with a display list, that is, free lists are joined together using a two-way list. When allocating memory, MALloc traverses all free blocks through an implicit linked list and selects the required blocks for allocation. When memory is merged, Malloc uses boundary marking to decide whether to merge blocks based on whether the blocks before and after each block have been allocated.

When the requested memory is less than 128K, BRK is used for heap allocation. If the requested memory is greater than 128K, mMAP is used to allocate the memory in the mapping area.

3. Classification of memory leaks

2. System resource leak: a program uses a resource allocated by the system and then does not have a corresponding function to release it, resulting in a waste of system resources. The destructor of the base class is not defined as virtual. When a base class pointer points to a subclass object, if the base destructor is not virtual, the subclass’s destructor is not called, and the subclass’s resources are not freed.

4. STL memory optimization

Use a secondary configurator structure. If the first level configurator allocates more than 128 bytes of memory, it will call the handle to release the memory if the allocation is not successful. If the allocation is not successful, it will throw exceptions. 2. Process applications smaller than 128 bytes. First expand the application space to a multiple of 8, then look up a sublist of the corresponding size from a freelist. If there is no memory attached to the free linked list, or if there are too few memory blocks attached to the list, it applies to the memory pool, generally 20 memory blocks. If the memory pool space is sufficient, fetch the memory. If not, allocate the maximum number of blocks to the free list. If none is available, attach the remaining memory to the most suitable free linked list. Malloc is then called to request space from the heap, and if the request fails to see if there are any blocks available on the free list, if not, the first level space configuration is called.