Introduction of C and delete in C++

  • 2020-06-12 10:06:15
  • OfStack

introduce

1. Differences between malloc,free and new,delete.

a. malloc,free is the standard library function of C/C++. new,delete is the operator for c++. b.malloc requests memory, not strictly "object". new requests "object", and new calls the constructor, which returns a pointer to the object. c. For class types, new/delete must be used to create and destroy, automatically calling the constructor and destructor. malloc/free cannot do this.

2. new is used according to the following principles:

a. The memory requested with new must be freed with delete. Memory requested with new[] must be freed with delete[]. c.delete free memory, pointer value does not change, a good style is to set pointer to NULL after free, for example,delete p; p = NULL.

use

1. Apply for an object


 int* p1 = new int;
 delete p1;
 p1 = NULL;

2. Apply for multiple objects


 int* p1 = new int[12];
 delete[] p1;
 p1 = NULL;

3. Apply for an char array of length 1024


 char* pArray = new char[1024];
 for (int i=0; i < 1024; i++)
 {
 pArray[i] = i;
 }
 delete[] pArray;
 pArray = NULL;

4. Apply for a class object


#include <stdio.h>
class Student
{
public:
 char name[32];
 int age;
};
int main()
{
 Student* pStu = new Student();
 delete pStu;
 pStu = NULL;
 return 1;
}

5. Apply for 1024 class objects


#include <stdio.h>
class Student
{
public:
 int age;
 Student()
 {
 ...
 }
 ~Student()
 {
 ...
 }
};
int main()
{
 Student* pStu = new Student[1024];
 for (int i=0; i<1024; i++)
 {
 pStu[i].age = i+1;
 }
 delete[] pStu;
 pStu = NULL;
 return 1;
}

new multiple objects cannot pass arguments, so the class must have a default constructor.

conclusion


Related articles: