New is a keyword in C + + that is used to dynamically request memory space. Delete is used to delete a space object that is requested by new.
To get a deeper understanding of new, see: http://blog.csdn.net/songthin/article/details/1703966
the difference between delete p and delete [] P:
1, int* p = new int (20);
Delete p;
2, int*p = new int[10] ();//array with initialization
delete [] p;
From the two small examples above, you can see that delete p is used to remove a single element, and delete [] p is used to delete an array element. Note: When deleting an array element, compiling with delete [] p will be correct, but the meaning will be different.
About the wild pointer after delete:
As shown in 1, 2, when the pointer is removed, the pointer becomes a dangling pointer (dangling pointer). The dangling pointer points to the memory where the object was stored, but the object no longer exists. The dangling pointer often causes the program to mistake me, and it is generally difficult to detect. So once the object is deleted, the pointer is set to 0 immediately, for example, delete p; p = NULL;
Here is an article about dangling pointers: quoting the original http://blog.sina.com.cn/s/blog_6405313801013jvg.html
- #include <iostream>
- using namespace Std;
- int main ()
- {
- int *p = new int;
- *p = 3;
- cout<< "after assigning 3 to P's address, the value read by the pointer P:" <<*p<<endl;
- Delete p;
- cout<< "After deleting the space, the pointer p reads the value:" <<*p<<endl;
- Long *p1 = new long;
- *P1 = 100;
- cout<< "P1 value:" <<*p1<<endl;
- cout<< value of "P:" <<*p<<endl;
- cout<< "After creating a new space, save the address in the pointer p:" <<p<<endl;
- cout<< "Pointer to new space P1 saved address:" <<p1<<endl;
- *p = 23;
- cout<< "The value that the pointer p reads after assigning 23 to P's address;" <<*p<<endl;
- cout<< "After assigning 23 to P's address, the pointer p1 the value read:" <<*p1<<endl;
- Delete P1;
- return 0;
- }
Operation Result:
The above code can be seen, after the deletion of the pointer p and the new pointer P1 point to the same piece of memory, the reason for this situation is actually due to the compiler. The compiler defaults to freeing up the memory space that is reclaimed and then allocating it to the newly opened space.
Welcome to Enlighten!
New and delete in C + +