The use of C++new and delete

The virtual address space of the executable program

insert image description here

  • Kernel: stores the operating system
  • Stack area: formal parameters of functions, non-static local variables, function field protection data, etc., the stack grows downward.
  • Memory-mapped area of ​​the shared library: used to load a shared dynamic memory library. Users can use the system interface to create shared memory for inter-process communication.
  • Heap area: used for dynamic memory allocation when the program is running, and the heap can grow upwards.
  • Data: store global data and static data, divided into .bss and .data.
  • Code: executable programs (machine instructions) and constant data.

1. new operator usage (keyword)

int* p= new int(10);

The usage of new here is used as an operator. There are four steps in this usage:

  1. calculation type
  2. Apply for a space (because the bottom layer of new is malloc)
  3. Initialize the acquired space
  4. Return the applied address

2. New function usage

When new is used as a function, similar to malloc, it applies for a space. The difference is that the return value is different; when the space is insufficient, malloc will return a "nullptr", and operator new will return a throw_bad exception.
insert image description here
When we add a nothrow:
insert image description here
After the application is wrong, we return a null pointer.

We cannot initialize malloc, nor can new.

So when new is used as a function, it is equivalent to malloc.

3. Position new

The usage of positioning new is very similar to constructing new. It is to construct an object in the determined space and place the object in the declared space.

int main()
{
    
    
	int n = 10;
	int* ipa = (int*)ma11oc(sizeof(int));
	int* ipb = (int*) : :operator new(sizeof(int) * n);
	new(ipa) int(20);
	new(ipb) int[]{
    
     1,2,3,4,5,6,7,8,9 };
	free(ipa);
	: :operator delete(ipb);
	return 0;
}

There is no need to open up the corresponding space. The legal space can be given a certain address and the corresponding operation can be performed according to the requirements.

4.new creates an object

New creates object characteristics:

  1. New creates an object that requires pointer reception, initialization in one place, and use in multiple places.
  2. The object created by new needs to be destroyed by delete.
  3. Objects created with new use heap space directly, while objects defined locally without new use stack space.
  4. The new object pointer has a wide range of uses, such as function return values, function parameters, and so on.
  5. Frequent calls are not suitable for new, just like new application and release of memory.

New creates an object example:

CTest*  pTest = new  CTest();
delete pTest;

pTest is used to receive object pointers.
Instead of new, directly use the class definition declaration:

CTest  mTest;

This kind of creation method does not need to be released manually after use, and the destructor of this class will be executed automatically.
For the object of new application, the destructor will be executed only when delete is called. If the program exits without executing delete, it will cause a memory leak.

C Test*  pTest = NULL;

However, the class object created in the normal way has allocated memory space at the beginning of creation.
This kind of pointer, if it has not been initialized by the object, does not need to be released by delete.

5.delete

The general format used by the delete operator is

 delete [ ]指针变量

For example, to undo the space created above with new:

delete p; 

If we use the character array space opened up by "new char[10];" and assign the pointer returned by new to the pointer variable pt, the space should be revoked with the delete operator of the following form:

  delete [] pt;

Generally speaking, delete and new need to be used in pairs.

6. The built-in types new/delete/malloc/free can be mixed

  1. new/delete are operators in C++. malloc/free are functions.
  2. When malloc applies for memory space, manually calculate the required size, new only needs the type name, and automatically calculates the size;
  3. The memory space requested by malloc will not be initialized, but new can be initialized;
  4. The return value of malloc is void*, which must be forced when receiving, and new does not need it;
  5. When malloc fails to apply for memory space, it returns NULL, which must be judged as empty; when new fails to apply for memory space, it returns an exception

7. Precautions for use

  1. If the dynamic allocation fails, a null pointer (NULL) is returned, indicating that an exception has occurred, the heap resources are insufficient, and the allocation failed.

  2. Pointer deletion and heap space release. Deleting a pointer p (delete p;) actually means deleting the target (variable or object, etc.) pointed to by p and releasing the heap space it occupies, rather than deleting p itself (the pointer p itself is not revoked, it itself still exists, the memory space occupied by the pointer has not been released), after releasing the heap space, p becomes a null pointer.

  3. Memory leaks and double releases. new and delete are used in pairs, and delete can only release heap space. If the pointer value returned by new is lost, the allocated heap space cannot be reclaimed, which is called a memory leak. It is also dangerous to release the same space repeatedly, because the space may have been allocated elsewhere, so the pointer returned by new must be properly preserved to ensure that it does not happen For memory leaks, it must also be ensured that the heap memory space will not be released repeatedly.

  4. The lifetime of a dynamically allocated variable or object. We also call the heap space as free space (free store), but we must remember to release the heap space occupied by the object, and it can only be released once. It is created inside the function and released outside the function, which often leads to errors.

  5. To access the structure space opened by new, it cannot be accessed directly through the variable name, but only through the assigned pointer.

    The address space can be dynamically opened and revoked with new and delete. When programming, if you use up a variable (usually temporarily stored data), you need to use it again next time, but you want to save the effort of reinitialization, you can open up a space every time you start using it, and use it again when it is used up. then undo it.

Guess you like

Origin blog.csdn.net/weixin_56935264/article/details/124858025