Freeing Memory with delete
Using new
to request memory when you need it is just the more glamorous half of the C++ memory-management package. The other half is the delete
operator, which enables you to return memory to the memory pool when you are finished with it. That is an important step toward making the most effective use of memory. Memory that you return, or free, can then be reused by other parts of the program. You use delete
by following it with a pointer to a block of memory originally allocated with new
:
int * ps = new int; // allocate memory with new. . . // use the memorydelete ps; // free memory with delete when done
This removes the memory to which ps
points; it doesn’t remove the pointer ps
itself. You can ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.