【C++ Language Basics】Summary

Point me –> C++ memory
point me –> object-oriented
point me –> STL
point me –> new features

[Operating System] Summary and Answers of Frequently Asked Questions
[Database] Summary and Answers of Frequently Asked Questions
[Computer Network] Summary and Answers of Frequently Asked Questions

This article directory

1. Briefly describe the characteristics of C++ language

  • C++ introduces an object-oriented mechanism on the basis of C language, and is also compatible with C language ;
  • C++ has three major features: encapsulation, inheritance, and polymorphism;
  • The program written in C++ language has a clear structure, is easy to expand, and has good program readability;
  • The code generated by C++ is of high quality and high operating efficiency , only 10% to 20% slower than assembly language;
  • C++ is safer , adding const constants, references, four types of cast conversion (static_cast, dynamic_cast, const_cast, reinterpret_cast), smart pointers, try-catch, etc.;
  • C++ has high reusability , and C++ introduces the concept of templates . On this basis, it implements the standard template library STL (Standard Template Library) for easy development;
  • At the same time, C++ is an ever-evolving language. Subsequent versions of C++ have developed many new features, such as the introduction of nullptr, auto variables, Lambda anonymous functions, rvalue references, and smart pointers in C++11.

2. Talk about the difference between C language and C++

  • C language is a subset of C++, and C++ is well compatible with C language ; however, C++ has many new features, such as references, smart pointers, auto variables, etc.;
  • C++ is an object-oriented programming language, and C language is a process-oriented programming language;
  • C language has some unsafe language features, such as the potential danger of pointer use, the uncertainty of forced conversion, memory leaks, etc.; and C++ has added many new features to improve security, such as const constants, references , casts conversions, smart pointers, try - catch, etc.;
  • C++ has high reusability . C++ introduces the concept of templates . On this basis, the standard template library STL for easy development is realized. Compared with the function library of C language, the STL library of C++ is more flexible and more general.

3. Talk about the difference between struct and class in C++

  • Access control : In struct, members are public by default, while in class, they are private by default. That is, in a class, the access level must be explicitly specified to access the member. For example:
struct S {
    
    
    int x;  // 默认:公共成员
};

class C {
    
    
    int x;  // 默认:私有成员
public:
    void setX(int value) {
    
     x = value; }  // 需要显式设置public访问级别
    int getX() {
    
     return x; }
};
  • Inheritance method : In class, the default inheritance method is private inheritance (private), while in struct, it is public inheritance (public). For example:
struct Base {
    
    
    void foo() {
    
    
        std::cout << "Base::foo()" << std::endl;
    }
};

struct Derived1 : Base {
    
     };   // 公共继承
class Derived2 : Base {
    
     };   // 私有继承

int main() {
    
    
    Derived1 d1;
    d1.foo();  // OK,公共继承

    Derived2 d2;
    d2.foo();  // 错误,私有继承
}

It can be seen that the member function foo() inherited from Base by Derived1 can be used directly in Derived1, but not Derived2.

  • The class keyword can be used to define template parameters, just like typename, while struct cannot be used to define template parameters.

4. Talk about the order of include header files and the difference between double quotes "" and angle brackets <>

  • the difference:
    • Header files in angle brackets <> are system files , and header files in double quotes "" are custom files .
    • The path to look for header files in the compiler preprocessing phase is different.
  • Find path:
    • The search path of the header file using angle brackets <>: the header file path set by the compiler –> system variable.
    • The search path of the header file using double quotes "": current header file directory –> header file path set by the compiler –> system variable.

5. Talk about the difference between C language structure and C++ structure

  • C language does not allow functions to exist in the body of the structure, C++ allows internal member functions, and allows the function to be a virtual function.
  • The C language structure can only have public access to internal member variables, while C++ allows three types: public, protected, and private.
  • The structure of C language cannot be inherited, and the structure of C++ can be inherited from other structures or classes.
  • To use a structure in C language, you need to add the struct keyword, or use typedef to get an alias for the structure, but in C++, you can omit the struct keyword and use it directly. For example:
struct Student
{
    
    
	int age;
	string name;
};

struct Student stu1; // C语言中正常使用

typedef struct Student Student2; // C语言中取别名
Student2 stu2; // C语言中通过取别名的使用

Student stu3; // C++中使用
Comparison item C language C++
member function not allowed Can
static member not allowed Can
Access control The default is public and cannot be modified public/private/protected
inheritance relationship cannot inherit Inheritable from classes or other structures
initialization Data members cannot be initialized directly Can

6. Talk about the keywords for importing C functions, and what is the difference between C++ compilation and C language

  • Keyword : In C++, the keyword for importing C functions is extern, and the expression form is extern "C". The main function of extern "C" is to correctly implement C++ codes to call other C language codes. After adding extern "C", it will instruct the compiler to compile this part of the code as C language , not C++.
  • Compilation difference : Since C++ supports function overloading, the compiler will add the parameter type of the function to the compiled code during the process of compiling the function, not just the function name ; while the C language does not support function overloading, Therefore, when compiling the function of C language code, the parameter type of the function will not be brought, and generally only the function name is included .
// extern示例:在C++程序里边声明该函数,会指示编译器这部分代码按C语言的进行编译
extern "C" int strcmp(const char* s1, const char* s2);

// 在C++程序里边声明该函数
extern "C" 
{
    
    
	#include <string.h> //string.h里边包含了要调用的C函数的声明
} 
//两种不同的语言,有着不同的编译规则,比如一个函数fun,可能C语言编译的时候为_fun,而C++则是__fun__

7. Briefly describe the process of C++ from code to executable binary file

C++ is similar to C language. A C++ program has four processes from source code to executable file: precompilation, compilation, assembly, and linking.

  • Precompilation : The main processing operations of this process are as follows:
    • Delete all #define and expand all macro definitions;
    • Handle all conditional precompiled directives, such as #if, #ifdef;
    • Process the #include precompiled directive, and insert the included file into the position of the precompiled directive;
    • filter all comments;
    • Add line number and filename identifiers.
  • Compilation : The main processing operations of this process are as follows:
    • Lexical analysis: splitting the character sequence of the source code into a series of tokens;
    • Syntactic analysis: perform grammatical analysis on tokens to generate a syntax tree;
    • Semantic analysis: judging whether the expression is meaningful;
    • Code optimization;
    • Object code generation: generate assembly code;
    • Object code optimization.
  • Assembly : This process is mainly to convert assembly code into machine-executable instructions.
  • Linking : linking the target files generated by different source files to form an executable program. Links are divided into static links and dynamic links:
    • Static link : The function or process to be called has been linked into the generated executable file when linking. Even if you delete the static library, it will not affect the execution of the executable program; the generated static link library, The suffix is ​​.lib under Windows, and the suffix is ​​.a under Linux.
    • Dynamic linking : When linking, the called function code is not linked in, but in the process of execution, the function to be linked is found again. There is no function code in the generated executable file, and only the relocation information of the function is included. , so when you delete the dynamic library, the executable program cannot run. The generated dynamic link library has a suffix of .dll under Windows and a suffix of .so under Linux.

8. Talk about the role of the static keyword

  • Define global static variables and local static variables : add the static keyword in front of the variable. Initialized static variables will allocate memory in the data segment, and uninitialized static variables will allocate memory in the BSS (uninitialized data) segment. Static variables will always maintain their previous values ​​until the end of the program. It's just that global static variables and local static variables have different scopes.
  • Define a static function : Add the static keyword before the return type of the function, and the function is defined as a static function. Static functions can only be used in this source file.
  • Add the static keyword before the variable type, and the variable is defined as a static variable. Static variables can only be used in this source file .
  • In C++, the static keyword can be used to define static member variables in a class : using static data members, it can be stored as a global variable, but hidden inside the class. static Static data members in a class have a separate storage area, regardless of how many objects of that class are created. All static data members of these objects share this static storage space.
  • In C++, the static keyword can be used to define static member functions in a class : Similar to static member variables, static member functions can also be defined in a class. Just add the keyword static before the function. For example, static member functions are also part of the class, not part of the object. All static data members of these objects share this static storage space.

"Note": When calling a non-static member function of an object, the system will assign the starting address of the object to the this pointer of the member function. And static member functions do not belong to any object, so C++ stipulates that static member functions do not have this pointer (emphasis). Since it does not point to an object, it cannot access non-static members of an object.

9. Talk about the difference between arrays and pointers

  • The definitions are different : an array is a collection used to store multiple data of the same type, and the array name is the address of the first element. A pointer is equivalent to a variable, but it is different from other variables. It stores the address of other variables in memory, and the pointer name points to the first address of the memory.
  • Memory allocation : The memory allocation of arrays is static, which means that the size of the array is determined at compile time. Pointers can dynamically allocate memory, which means that pointers can dynamically allocate memory at runtime using malloc() or similar functions.
  • Initialization : Arrays can be initialized at definition time or afterwards. Pointers can be initialized to NULL at definition time, but memory will not be allocated.
  • Use : The array can directly access the elements, for example, the first element of the array can be called arr[0]. The pointer must be dereferenced before the pointed object can be accessed. For example, the pointed object can be accessed through *p.
  • Arithmetic operations : pointers can perform arithmetic operations, such as pointing to the next address, the previous address, adding an integer, etc. These operators are very useful in pointer manipulation. Arithmetic operations can be performed between different elements of the array, but they must be in integer units, and the memory addresses pointed to must be continuous.
  • Assignment : Pointer variables of the same type can be assigned to each other; arrays cannot, and can only be assigned or copied one by one.
  • Find sizeof : Find the memory size of the storage space occupied by the array as sizeof (array name) / sizeof (data type). On a 32-bit platform, sizeof (pointer name) is 4 regardless of the type of pointer, and on a 64-bit platform, sizeof (pointer name) is 8 regardless of the type of pointer.

10. Talk about what is a function pointer, how to define a function pointer, and what are the usage scenarios

  • A function pointer is a pointer to a function, i.e. it contains the address of the function . Function pointers can be passed to functions like ordinary pointers, and can also be used as function return values. Different functions can be easily called using function pointers to match parameter and return value types.
  • In C++, defining a function pointer requires specifying the function name, parameter types, and return type. For example, the following is the definition of a pointer to a function that takes two integer arguments and returns an integer:
int (*funcPtr)(int, int);

In this definition, funcPtr is a pointer to a function that accepts two integer parameters and returns an integer. To use a function pointer, it needs to be initialized to the address of a function. For example, the following is an example of initializing funcPtr to the address of the function add:

#include <iostream>
using namespace std;

int add(int x, int y) {
    
    
    return x + y;
}

int main() {
    
    
    int (*funcPtr)(int, int) = &add;
    int result = (*funcPtr)(3, 4); // 调用函数指针
    cout << "result = " << result << endl; // result = 7
    return 0;
}

In this example, funcPtr is initialized to the address of the add function, and the function pointer is then called by prefixing it with a *, passing two integer arguments (3 and 4). The final result is stored in the result variable.

  • Common scenarios for using function pointers include dynamically selecting a function to call at runtime, as callback functions (such as in event handling), and in function templates. Function pointers can also be used to implement arrays of function pointers and structures of function pointers to provide more flexible program structures.
    Callback (callback): We call the API function (Application Programming Interface) provided by others, which is called Call; if someone else's library calls our function, it is called Callback.

11. Talk about when static variables are initialized

  • For global and static variables in the C language, initialization occurs before any code is executed and is a compile-time initialization.
  • The C++ standard stipulates that a global or static object is constructed if and only when the object is used for the first time.

12. Tell me, can nullptr call a member function, why?

able. Because the object is bound to the function address at compile time , it doesn't matter whether the pointer is empty or not.

Example:

#include<iostream>
using namespace std;

class Animal
{
    
    
public:
	void sleep()
	{
    
    
		cout << "Animal sleep()" << endl;
	}
	void breathe()
	{
    
    
		cout << "Animal breathe()" << endl;
	}
};

class Fish :public Animal
{
    
    
public:
	void breathe()
	{
    
    
		cout << "Fish breathe()" << endl;
	}
};

int main()
{
    
    
	Animal* ani = nullptr;
	ani->breathe(); // Animal breathe()

	Fish* fis = nullptr;
	fis->breathe(); // Fish breathe()

	return 0;
}

Reason: Because the object is bound to the function address at compile time, it has nothing to do with whether the pointer is empty or not. ani->breath(); When compiling, the address of the function is bound to the pointer ani; call breath(*this), this is equal to ani. Since there is no need to dereference this in the function, the function will run without error, but if this is used, because this=nullptr, the operation will fail.

13. Talk about what is a wild pointer, how it is generated, and how to avoid it

  • Concept : A dangling pointer is a pointer to a freed or unallocated memory area. When a program tries to use wild pointers, it can cause unpredictable behavior such as crashes, data corruption, and other serious problems.
  • Wild pointers are usually caused by the following situations :
    • Manipulating freed memory, such as deleting a pointer and trying to use it later.
    • Manipulating unallocated memory, such as using uninitialized pointers.
    • Manipulating a pointer that has gone out of scope, such as allocating the memory of a local variable inside the function, and then returning a pointer to the memory when returning from the function.
  • Ways to avoid wild pointers :
    • After freeing the memory, assign the pointer to nullptr (null pointer). This prevents a pointer from being used for already freed or unallocated memory.
    • Avoid uninitialized pointers, you can usually do this by initializing the pointer to nullptr.
    • Always check for nullptr before using a pointer. This can help avoid accessing unallocated or freed memory.
    • If the pointer is only used to access local variables inside the function, it should be set to nullptr when the function exits.
    • Use the memory allocation functions of the C language with caution. After allocating memory, always check whether the pointer is nullptr. And properly free the allocated memory.
    • Use smart pointers.

14. Talk about static local variables, global variables, characteristics of local variables, and usage scenarios

  1. static local variable

A static local variable is a variable defined within a function, but its value remains unchanged during the execution of the function. A static local variable is initialized only once and can only be accessed inside the function in which it is defined. Variables of this type remain in the program's memory until the program ends. The definition format of a static local variable is:

static int count = 0;

Features of static local variables:

  • Long life cycle: Static local variables are only initialized once, and the value of the variable will be retained after the function call ends.
  • Can only be accessed inside the function that defines the variable: Static local variables can only be accessed inside the function that defines the variable, and cannot be used by other functions.
  • The default value is 0: Static local variables that have not been initialized will be assigned the value 0 by default.
  • Addresses are assigned at compile time: Static local variables are assigned addresses at compile time, so their access speed is very fast.

Usage scenarios of static local variables:

  • A counter needs to be maintained inside the function, and the last result needs to be kept after calling the function each time, so static local variables can be used.
  1. global variable

A global variable is a variable defined outside a function, which can be accessed inside any function. After the global variable is created, it exists throughout the life cycle of the program, unless it is explicitly destroyed by the program. The definition format of global variables is:

int count = 0;

Features of global variables:

  • Long life cycle: Once a global variable is defined, it will always exist during the running of the entire program.
  • Can be accessed anywhere in the program: Global variables can be accessed anywhere in the program, but in the case of local variables with the same name, local variables will be accessed first.
  • Use with caution: Global variables are shared by all functions, which are prone to problems such as naming conflicts and data pollution, so use with caution.

Usage scenarios of global variables:

  • Global variables can store global configuration, status, count and other information, and can be accessed by all functions.
  • Global variables can be used to transfer data in a program, such as sharing the same data in different functions.
  1. local variable

A local variable is a variable defined inside a function, it can only be accessed inside the defined function, and will be automatically destroyed after leaving the scope of the function. The definition format of a local variable is:

int count = 0;

Features of local variables:

  • Short life cycle: Local variables end with the end of the function call during the execution of the function, and are automatically destroyed after leaving the scope of the function.
  • It can only be accessed inside the defining function: a local variable can only be accessed within the function to which it belongs, and cannot be accessed by external functions.
  • Different values ​​with the same name: You can declare local variables with the same name in different functions, and the variable names do not have to be unique.

Usage scenarios of local variables:

  • Some temporary variables need to be defined inside the function, which will be automatically destroyed after the function is executed, and local variables can be used.
  • The same variable name needs to be declared in different functions, but different variables are assigned different values, and local variables can be used.

15. Talk about the difference between inline functions and macro functions

Both C++ inline functions and macro functions can be used to replace code blocks in a program to improve code execution efficiency. However, they have some differences:

  • An inline function is a function that is processed by the compiler, and the compiler copies the code of the inline function to the code that calls it, so as to avoid additional overhead when calling the function. The macro function is a simple string replacement, the compiler will not process the code of the macro function, but directly replace it with its definition.
  • Inline functions can handle complex parameter types and expressions, while macro functions cannot. Inline functions check that the parameter types are correct, while macro functions do not, which can lead to type mismatch errors.
  • Inline functions can have local variables and control statements like ordinary functions, but macro functions cannot. An inline function is a code block processed by the compiler, which can include local variables, if statements, while loops, etc. like ordinary functions. However, since the macro function is a simple code replacement, it does not create local variables, and does not process control statements such as if statements and while loops.
  • Inline functions are defined in header files and can be called by multiple source files, while macro functions can be defined anywhere, but can only be used in the current file.

The following are code samples for inline functions and macro functions:

  • Examples of inline functions
#include <iostream>
using namespace std;

// 定义内联函数
inline int add(int a, int b)
{
    
    
    return a + b;
}

int main()
{
    
    
    int a = 5, b = 3;
    // 调用内联函数
    int c = add(a, b);
    cout << "a + b = " << c << endl;
    return 0;
}
  • Macro function example
#include <iostream>
using namespace std;

// 宏函数的定义
#define ADD(a, b) ((a) + (b))

int main()
{
    
    
    int a = 5, b = 3;
    // 调用宏函数
    int c = ADD(a, b);
    cout << "a + b = " << c << endl;
    return 0;
}

As can be seen, the syntax for using macro functions and inline functions is somewhat different. When using an inline function, you need to add the inline keyword before the function declaration; while the macro function is directly defined with #define. However, in the actual programming process, you should try to avoid using macro functions, because it may cause problems such as type mismatch and ambiguous semantics, while inline functions are safer and easier to use.

Some precautions when using :

  • When using macro definitions, you must pay attention to the occurrence of error conditions. For example, the macro definition function does not have type checking, and any type may be passed in, which will cause errors. There is also the use of parentheses. Macro parameters should be carefully handled when defining macros. Generally, they are enclosed in parentheses, otherwise ambiguity will easily appear.
  • Inline functions are generally used for relatively small, frequently called functions, which can reduce the overhead caused by function calls. You can designate a function as an inline function by simply adding the keyword inline before the return type of the function.
  • Different from other functions, it is better to define the inline function in the header file instead of just declaring it, because when the compiler processes the inline function, it needs to expand the function inline at the call point, so it is not enough to only need the function declaration .

Conditions for use of inline functions :

  • Inlining is at the cost of code expansion (copying), which only saves the overhead of function calls, thereby improving the execution efficiency of functions. If the execution time of the code in the function body is relatively large compared to the overhead of the function call, then the efficiency gains will be small. On the other hand, every inline function call needs to copy the code, which will increase the total code size of the program and consume more memory space. The following situations should not be used inline:
    • If the code in the function body is relatively long, using inlining will result in high memory consumption costs.
    • If there is a loop in the function body, the time to execute the code in the function body is greater than the overhead of the function call.
  • Inlining cannot be expanded at any time. A good compiler will automatically cancel inlining that does not meet the requirements according to the definition body of the function.

16. Talk about the difference between operators i++ and ++i

  • The order of assignment is different: ++i is added first and then assigned; i++ is assigned first and then added. Both ++i and i++ are done in two steps.
  • Efficiency is different: post ++ executes slower than pre.
  • i++ cannot be an lvalue, but ++i can.
int i = 0;
int* p1 = &(++i);//正确
// int* p2 = &(i++);//错误
++i = 1;//正确
// i++ = 1;//错误
  • Neither are atomic operations.

17. Talk about the difference between new and malloc, and the underlying implementation principles of each

The difference between the two :

  • new is an operator, and malloc is a function.
  • When new is called, memory is allocated first, then the constructor is called, and the destructor is called when it is released; while malloc has no constructor and destructor.
  • malloc needs to specify the size of the requested memory, and the returned pointer needs to be forcibly transferred; new will call the constructor without specifying the size of the memory, and the returned pointer does not need to be forcibly transferred.
  • new can be overloaded, malloc cannot.
  • new allocates memory more directly and safely.
  • new throws an exception when an error occurs, and malloc returns null.

The underlying implementation of malloc : when the allocated space is less than 128K, call brk(); when the allocated space is greater than 128K, call mmap(). malloc uses a memory pool management method to reduce memory fragmentation. First apply for a large block of memory as the heap area, and then divide the heap area into multiple memory blocks. When the user applies for memory, a suitable free block is directly allocated from the heap area. An implicit linked list is used to store all free blocks, and each free block records an unallocated, continuous memory address.

The underlying implementation of new : The keyword new actually performs the following steps when calling the constructor:

  • create a new object;
  • Assign the scope of the constructor to this new object (so this points to this new object);
  • Execute the code in the constructor (add properties to this new object);
  • Return the new object.

18. Talk about the difference between const and define

const is used to define constants, and define is used to define macros, and macros can also be used to define constants. When both are used for constant definition, their differences are:

  • const takes effect at the compilation stage, and define takes effect at the preprocessing stage.
  • Constants defined by const are stored in memory in C language and require additional memory space. The constant defined by define is a direct operand at runtime and will not be stored in memory.
  • Constants defined by const are typed, and constants defined by define are untyped. Therefore, the constant defined by define is not conducive to type checking.
  • The domain of definition is different: const constants are only valid within the domain of definition, while define macros are not restricted by the domain of definition.

19. Talk about the difference between function pointer and pointer function in C++

  1. Definition and usage of function pointer

A function pointer is a pointer to a function, which is used to store the address of the function. In C++, the definition format of a function pointer is:

return_type (*pointer_name)(parameter1_type, parameter2_type, ...);

Among them, return_type indicates the return value type of the function, pointer_name is the name of the pointer, and parameter1_type, parameter2_type, etc. are the types of function parameters.

There are two main usages of function pointers:

  • Pass a function pointer as an argument to a function:
void function(int parameter, void (*pointer_name)(int)) {
    
    
    pointer_name(parameter);
}
  • Use function pointers as variables:
int add(int x, int y) {
    
    
    return x + y;
}

int main() {
    
    
    int (*func_ptr)(int, int);
    func_ptr = add;
    int result = func_ptr(1, 2);
    return 0;
}

In the above example, we first define a function pointer func_ptr, and then assign the address of the function add to it. Next, we call the function add through func_ptr and calculate the result.

From the perspective of usage, function pointers are mainly used for passing functions as data, dynamically calling functions, and constructing arrays of function pointers.

  1. Definition and usage of pointer function

A pointer function is a function that returns a pointer type, and its return value is a pointer. In C++, the definition format of a pointer function is:

data_type* function_name(parameter1_type, parameter2_type, ...)

Among them, data_type indicates the data type pointed by the pointer, function_name is the function name, parameter1_type, parameter2_type, etc. are the types of function parameters.

The usage of pointer functions can be simply summarized into the following two categories:

  • Returns a pointer to heap memory:
int* create_array(int size) {
    
    
    int* arr = new int[size];
    return arr;
}

In the above example, we use the new keyword to create a dynamic array and return its pointer.

  • Return a pointer to static or global memory:
char* get_message() {
    
    
    static char message[] = "Hello world";
    return message;
}

In the above example, we define a static character array message and use it as the return value of the pointer function.

From the perspective of usage, pointer functions are mainly used to return pointers to heap memory or static/global memory, and to process complex data structures and objects.

"Summary": Although both function pointers and pointer functions are related to pointers, their meanings and usages are quite different. Function pointers are mainly used to pass functions as data, dynamically call functions, and construct function pointer arrays, while pointer functions are mainly used to return pointers to heap memory or static/global memory, and to handle complex data structures and objects.

20. Tell me what const int *a, int const *a, const int a, int *const a, const int *const a are and what are their characteristics

const int a;          // a是一个常量,不允许修改
const int* a;         // a指针所指向的内存里的值不变,即 (*a) 不变
int const* a;         // 同 const int *a;
int* const a;         // a指针所指向的内存地址不变,即a不变
const int* const a;   // 都不变,即 (*a) 不变,a也不变

21. Talk about what to pay attention to when using pointers

  • Pointer Null Check: Before using a pointer, it needs to be checked for NULL. If the pointer is NULL, it means that the pointer does not point to any valid memory location, and further operation may cause the program to crash.
  • Dangling pointer problem: A dangling pointer means that the memory location pointed to by the pointer has been released or expired, but the pointer still points to this location. At this time, the value or modification of the pointer will cause unknown errors.
  • Pointer out of bounds: When the memory range of the pointer operation exceeds the memory area allocated to it, it will cause the pointer to out of bounds, which may cause the program to crash or the data to be destroyed.
  • Memory leak: When using dynamically allocated memory, you need to ensure that it is released after use, otherwise it will cause a memory leak and reduce the available memory of the system.
  • Multi-level pointers: If you use multi-level pointers, you need to ensure that you understand the level of the pointer and the memory area it points to to avoid unnecessary errors.
  • Pointer arithmetic: When using pointer operations, it is necessary to ensure the correctness and safety of the operations, otherwise the memory data will be destroyed and the program will crash.
  • Pointer type: When declaring and using a pointer, you need to ensure that the pointer type matches the type of the memory location it points to, otherwise it will cause a data type mismatch error.
  • Pointer alias: Pointer alias means that two or more pointers point to the same memory location. At this time, if one pointer is modified, it will affect the memory location pointed to by other pointers, which may cause unnecessary errors.

22. Talk about the difference between inline functions and functions, and the role of inline functions

difference :

  • Inline functions have more keyword inline than ordinary functions ;
  • Inline functions avoid the overhead of function calls , and ordinary functions have the overhead of calling;
  • Ordinary functions need to be addressed (function entry address) when they are called , and inline functions do not need to be addressed;
  • Inline functions have certain restrictions. Inline function bodies require simple code and cannot contain complex structural control statements. Ordinary functions do not have this requirement.

The function of the inline function : When the inline function is called, the call expression is replaced by the inline function body. Avoid the overhead of function calls.

"Notice":

  • Loop statements and switch statements are not allowed in inline functions: if the inline function has these statements, the compiler will treat the function as a normal function and generate function call code, and recursive functions cannot be used as inline functions. Inline functions are only suitable for small functions with only 1 to 5 lines. For a large function with many statements, the overhead of function calling and returning is relatively insignificant, so there is no need to implement it with inline functions.
  • The definition of an inline function must appear before the inline function is called for the first time.
  • The inline statement is just a suggestion, and whether to inline is determined by the compiler, so it is not actually controllable.

23. Briefly describe how C++ has several ways of passing values, and what is the difference between them

There are three ways of passing parameters: passing by value, passing by reference, and passing by pointer.

  • Value transfer : Even if the value of the formal parameter changes in the function body, it will not affect the value of the actual parameter;
  • Transfer by reference : the value of the formal parameter changes in the body of the function, which will affect the value of the actual parameter;
  • Pointer passing : On the premise that the pointer pointing does not change, the value of the formal parameter changes in the function body, which will affect the value of the actual parameter.

"Summary": When value transfer is used for objects, the entire object will be copied, which is inefficient. When the reference is passed to the object, the copy behavior does not occur, but the object is bound, which is more efficient. Passing by pointer is the same, but not as safe as passing by reference.

Code example:

#include <iostream>
using namespace std;

void testfunc(int a, int* b, int& c) 
{
    
    
	// 形参a的值发生了改变,但是没有影响实参i的值
	// 但形参*b、c的值发生了改变,影响到了实参*j、k的值
	a += 1;
	(*b) += 1;
	c += 1;
	cout << "a = " << a << endl;  // 2
	cout << "b = " << *b << endl; // 2
	cout << "c = " << c << endl;  // 2
} 

int main() 
{
    
    
	int i = 1;
	int a = 1;
	int* j = &a;
	int k = 1;
	testfunc(i, j, k);
	cout << "i = " << i << endl;  // 1
	cout << "j = " << *j << endl; // 2
	cout << "k = " << k << endl;  // 2

	return 0;
}

24. Briefly describe the difference between pointer constants and constant pointers

  • A pointer constant means that a pointer is defined, and the value of this pointer can only be initialized when it is defined, and cannot be changed elsewhere. A constant pointer means that a pointer is defined, which points to a read-only object, and the value of this object cannot be changed through a constant pointer.
  • The pointer constant emphasizes the immutability of the pointer, while the constant pointer emphasizes the immutability of the object it points to.
// const* 是常量指针,*const 是指针常量
int const* a; // a指针所指向的内存里的值不变,即 (*a) 不变
int* const a; // a指针所指向的内存地址不变,即a不变

25. What is the difference between variable declaration and definition

  • Declaration (variable declaration): Refers to the identification of the type and name of the variable in the program. Usually happens in header files, outside of the main function. It informs the compiler of the variable's existence, but does not allocate any storage for it. When declaring a variable, the compiler looks up the type and name of the variable and adds it to the symbol table.

For example, x and y in the following code are just declared, but no values ​​are assigned to them.

int x;
double y;
  • Definition (variable definition): In addition to the declaration, storage space is allocated to the variable. When defining a variable, the compiler will allocate memory space for the variable, and the size of the space depends on the size of the variable type. At the same time, variables can be initialized or assigned when they are defined.

For example, the following code defines two variables x and y of type int and initializes them.

int x = 10; 
int y(20);
  • Difference : The variable declaration indicates the type and name of the variable, but does not allocate memory space for it; the variable definition not only declares the type and name of the variable, but also allocates memory space for it, and can assign an initial value to the variable. A variable can be declared in multiple places, but defined in only one place. Adding extern modification is the declaration of the variable, indicating that the variable will be defined outside the file or in the back part of the file.

26. Write the if statement for comparing int, bool, float, and pointer variables with "zero value"

"Note": What is required in the title is a zero-value comparison, not a comparison with 0. In C++, the range of "zero value" is very large, which can be 0, 0.0, FALSE or "null pointer".

Here is the answer:

//int与零值比较 
if ( n == 0 )
if ( n != 0 )

//bool与零值比较 
if   (flag)   //表示flag为真 
if   (!flag)  //表示flag为假 

//float与零值比较 
const float EPSINON = 0.00001;
if ((x >= - EPSINON) && (x <= EPSINON)) //其中EPSINON是允许的误差(即精度)

//指针变量与零值比较 
if (p == NULL)
if (p != NULL)

Guess you like

Origin blog.csdn.net/m0_51913750/article/details/130319060