With malloc/free in c++, why do you need new/delete?

One: malloc/free is a standard library function in c/c++, and new/delete is an operator in c++. They are all used to allocate dynamic memory and free memory.

Two: For non-internal data objects (eg: class objects), only malloc/free cannot meet the requirements of dynamic objects. This is because the object needs to automatically execute the constructor when it is created, and the destructor is automatically executed before the object dies. Since malloc/free is a library function instead of an operator, it is not within the control authority of the compiler, so it cannot be automatically executed. Execute constructor and destructor. Therefore, the task of executing constructors and destructors cannot be imposed on malloc/free. Therefore, in C++, we need an operator new that can complete the work of dynamic memory allocation and initialization, and an operator delete that can complete the work of cleaning up and freeing memory.

three:

1: New creates an object, malloc allocates a memory area, which is accessed by a pointer, and the pointer can be moved in the area;

2: For internal data types, since there is no requirement for constructors and destructors, for internal data types, the functions of malloc/free and new/delete are equivalent, and they are used to apply for dynamic memory and release memory. .

Four: What are internal data types and non-internal data types?

1: The internal data type is recognized by the compiler itself and does not need to be defined by the user. Such as: basic data types: int, char, double, etc. are all internal data types; 2: non-internal data types are not recognized by the compiler itself, and need to be defined by the user to be recognized by the compiler. Such as: variables modified by keywords such as class, struct, union are all non-internal data types.

Five: Why is the library function not under the control of the compiler, but the operator?

The library function is the compiled code, the compiler will not compile and check, and the linker will synthesize the library and the code written by the user into the exe file. Whether the operator is correct can be determined by the compiler when compiling scan analysis.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324122733&siteId=291194637