<> review C

learn C++ You must have learned it before C bar ,C Language application space is opened up in the heap area , And the ways to apply are 3 species ;malloc,calloc and realloc.

malloc: Function prototype void* malloc(size_t size)
parameter size Is the number of bytes to allocate , The return value is void*, Usually we need to change to the type of space we need to apply for , Open successfully return to the first address of space , Failure will return NULL, However, initialization is not performed after the application is successful , Each data is a random value .

calloc: Function prototype void* calloc(size_t number, size_t size);
parameter number For the number of applications ;size For each data size , The return value is void*, Usually we need to change to the type of space we need to apply for , Open successfully return to the first address of space , Failure will return NULL, However, if the application is successful, the space will be initialized , And initially 0.

realloc: Function prototype void*realloc(void * mem_address, unsigned int newsize);
parameter address The first address of the space to be expanded , parameter newsize How many bytes of space to adjust for , The return value is void*, Usually we need to change to the type of space we need to apply for , Open successfully return to the first address of space , Failure will return NULL, However, initialization is not performed after the application is successful , Each data is a random value . Note that , Previously applied space reuse realloc To expand without releasing , Just release the expanded space

<>new & delete

C++ Is an object-oriented high-level language , In our code , It is often necessary to create and clean up object resources . And compatible malloc and free It can't meet our needs very well , thus C++ take malloc and free Packaged and given a new name
new and delete, The role of these two keywords is more than malloc and free It's powerful , It's also very convenient to use , Now let's take a look new and delete Usage of

<>new and delete Operations on built-in types

new and delete All operators , Not a library function , There is no need to add header files separately
format :
new
1, Type pointer Pointer variable name = new type
2, Type pointer Pointer variable name = new type ( Initial value )
3, Type pointer Pointer variable name = new type [ Number of elements ]
delete
1,delete Pointer variable name
2,delete[] Pointer variable name
// Application space int* ptr = new int; // Apply for space and initialize int* ptr2 = new int(1);
// Apply for continuous space , The space size is 4*10=40 int* arr = new int[10];//c++98 Continuous space initialization is not allowed // Free up a single space delete
ptr; delete ptr2; // Release continuous multiple spaces delete[] arr;
From the top , It's like that C Among them malloc It doesn't make much difference , Let's look at custom types , We can see the main difference between them .

<>new and delete Operations on custom types

malloc and free The initialization and resource cleaning of our custom type will not be completed , and new Can complete the initialization and maintenance of the object delete Can complete the object resource cleaning .
class A { public: A(int a = 10) :_a(a) { cout << "A() " << _a << endl; } ~A() {
cout<< "~A() " << endl; } private: int _a; }; void test() { A* pa1 = new A;
delete pa1; }

To sum up ,new To apply for an object, you first apply for the space of the object and call the object's constructor to complete the initialization of the object ;delete Will first complete the object resource cleaning , And then release the space occupied by the object .

But pay attention , If there is no default constructor , We have to be here new An object should be initialized by adding parentheses to give the initial value . There is no default constructor , We can't apply for multiple spaces in a row .
class A { public: A(int a) :_a(a) { cout << "A() " << _a << endl; } private:
int _a; }; void test() { //error, No default constructor A* pa1 = new A; delete pa1; //ok A* pa2
= new A(10); delete pa2; //error, No default constructor A* arr = new A[10]; delete[] arr; }
If there are more than one member variable in the class , Just put the value we want to assign to the object in parentheses , Separate with commas .
class A { public: A(int a = 1, int b = 2, int c = 3) :_a(a) ,_b(b) ,_c(c) {}
private: int _a; int _b; int _c; }; void test() { // Use incoming values A* pa1 = new A(10, 20
, 30); delete pa1; // Use default parameters A* pa2 = new A; delete pa2; // All use default parameters A* arr = new
A[10]; delete[] arr; }
<>operator new & operator delete

These two are global functions provided by the system , That's right malloc and free Encapsulated functions . and new and delete It encapsulates these two global functions .operator
new and malloc The biggest difference is when the application is wrong , It's handled differently .malloc Returns when the application fails NULL,operator new Exception will be thrown when the application fails

operator new How to use and malloc Very similar .
void test() { int* ptr = (int*)operator new(sizeof(int) * 2); operator delete(
ptr); // Application failed, exception thrown int* ptr1 = (int*)operator new(0x7fffffff); operator delete(ptr1
); }

<> heavy load operator new and operator delete

It says so ,new and delete Yes operator new and operator
delete Encapsulation of , In fact, we call new and delete, The system will also call the operator new and operator delete.
// Built in type //new-> operator new ->malloc int* ptr = new int; //delete-> operator
delete -> free delete ptr; // Custom type //new-> operator new ->malloc -> Constructors A* pa =
new A; // Destructor -> delete-> operator delete -> free delete pa;

And at work , We'll have multiple classes , There will also be multiple objects , Ordinary to apply for space will increase the cost of the system ,C++ The memory pool is introduced to reduce the system overhead , And it can improve the efficiency . The working principle of memory pool is to apply for larger space from the system at one time , Every time we apply for space, we directly use the space in the memory pool , The two overhead actions of application and release are omitted , It also reduces system memory fragmentation , Thus, the development efficiency is improved .

Overload code :
class ListNode { public: void* operator new(size_t n) { // Using memory pool cout <<
"operator new" << endl; allocator<ListNode> alloc; // Space Configurator return alloc.allocate
(1); } void operator delete(void* ptr) { cout << "operator delete" << endl;
allocator<ListNode> alloc;// Space Configurator alloc.deallocate((ListNode*)ptr, 1); } private
: int _data = 0; ListNode* _next = nullptr; }; void test() { ListNode* node =
new ListNode; delete node; }

The relationship between the three :
operator new = malloc + Fail to throw exception
new = operator new + Call constructor
new = malloc + Fail to throw exception + Call constructor
operator delete = free
delete = operator + Calling destructors
delete = free + Calling destructors

<> location new expression

location new The function of the expression is to initialize the existing space
Use format :new( Pointer name ) type ( Parameter value ( Optional ))
class A { public: A(int a) :_a(a) { cout << "A(int)" << endl; } ~A() { cout <<
"~A()" << endl; } private: int _a; }; void test() { A* pa = (A*)malloc(sizeof(A)
); // Initialize the existing space new(pa) A(10); // Display call deconstruction pa->~A(); free(pa); }

<>malloc/free and new/delete The difference between

* malloc and free It's a function ,new and delete It's an operator
* malloc The requested space will not be initialized ,new Can be initialized
* malloc When applying for space, you need to manually calculate the space size and transfer it ,new unwanted
* malloc The return value of is void*, When using, it must be forced to receive ,new unwanted
* malloc Return when application fails NULL,new If the application fails, an exception will be thrown
* When applying for an object of a custom type ,malloc/free Constructors and destructors are not called , and new The constructor is called after application space. ,delete The destructor is called before the space is freed

Technology