[C ++] "C ++ 17 Introduction to the classic" study notes 10 ---- pointer operators: new and delete

Assuming a double variable memory space needs to be a pointer to the type of double * pointer. Then during program execution, memory space allocated for the variable request.

One way is to:

double* pvalue {};
pvalue = new double;

Note that all pointers should be initialized. If the pointer does not contain a valid address, you should always let it contain nullptr.

In the above code, the second line of the new operator returns the memory address of a free store double variables assigned, it shall be stored in the address pointer pvalue. Followed by indirection operator can previously described, using the pointer referenced variables.

E.g:

*pvalue = 3.14; 

When the dynamic memory allocation variable is no longer needed, you can use the delete operator, releases the memory occupied by it:

delete pvalue;

delete operator releases memory, without changing the pointer.

The lifting of the suspension pointer references can cause serious problems, it should always be in the release pointer to memory, reset the pointer.

As follows:

delete pvalue;
pvalue = nullptr;

Now pvalue no longer point to anything. The pointer can not be used to access freed memory. Comprising nullptr pointer to store or retrieve data, which terminates the program immediately.

Nullptr pointer variable that contains the value of the application delete is safe. This statement does not have any effect. Therefore, if there is no need to use the following tests:

if (pvalue)
{
    delete pvalue;
    pvalue = nullptr;
}

Warning: Each new must correspond to a delete, each new [] must correspond to a delete []. If this does not correspond, it will lead to behavioral or memory leaks uncertain.


prompt:

In everyday coding, do not directly use the new, new [], delete, delete [] operator.

In modern C ++ code, without their foothold. You should always use std :: vector <> container (to replace or smart pointer) to dynamically allocated objects and manage their survival. These advanced alternative much safer than low-level memory management, clear all dangling pointer in the program immediately release many times, allocation / deallocation mismatch and memory leaks, provide great help to the programmer.

 


 

Guess you like

Origin blog.csdn.net/kingkee/article/details/94208868