new and delete must be used in pairs and cannot be mixed with malloc|free. The way you write may not be a problem for basic types, but once the constructor and destructor are involved No, it’s very important to develop habits. And the standard library doesn’t seem to stipulate that new must be implemented using malloc, so things in new still need to be delete, not free
Because the C++ standard does not require new memory allocation to be allocated by malloc, although some C++ implementations do this, but not all. Moreover, the new operator can be overloaded and custom memory allocation code can be written. In this case, it must not be free. In addition, for new class objects, free cannot be called because the destructor will not be called.
First of all: the bottom layer of new and delete is implemented using malloc and free Secondly: when it is a basic data type, delete and delete[] can be mixed Using free can also release the space created by new, but new [] sometimes cannot be used The key point is that it is best not to mix them
new
anddelete
must be used in pairs and cannot be mixed withmalloc|free
. The way you writemay not be a problem for basic types, but once the constructor and destructor are involved No, it’s very important to develop habits.
And the standard library doesn’t seem to stipulate that
new
must be implemented usingmalloc
, so things innew
still need to bedelete
, notfree
It’s better to use
delete
When using free, it is possible that the new object may not execute the destructor, which may cause a program error
It is not recommended to use it this way. Use new/delete and malloc/free together
Because the C++ standard does not require new memory allocation to be allocated by malloc, although some C++ implementations do this, but not all. Moreover, the new operator can be overloaded and custom memory allocation code can be written. In this case, it must not be free. In addition, for new class objects, free cannot be called because the destructor will not be called.
First of all: the bottom layer of new and delete is implemented using malloc and free
Secondly: when it is a basic data type, delete and delete[] can be mixed
Using free can also release the space created by new, but new [] sometimes cannot be used
The key point is that it is best not to mix them