天天看点

Managing Dynamic Memory Is Error-prone

There are three common programs with using and delete to manage dynamic memory.

  1. Forgetting to delete memory. Neglecting to delete dynamic is known as a "memory leak", because the memory is never turned to the free store. Testing for memory leaks is difficult because they usually cannot be detected until the application is run for a long enough time to actually exhaust memory.
  2. Using an object after it has been deleted. This error can sometimes be detected by making the pointer null after the delete.
  3. Deleting the same memory twice. This error can happen when two pointers address the same dynamically allocated object. If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may corrupted.

These kinds of error are considerably easier to make than they are to find and fix.

Best practices:

You can avoid all of these problems by using smart pointers exclusively. The smart pointer will take care of deleting the memory only when there are no remaining smart pointers pointing to that memory.---(From "C++ Primer(5th)")

Resetting the value of a pointer after a delete... (&& dangling pointer)

When we delete a pointer, that pointer becomes invalid. Although the pointer is invalid, on many machines the pointer continues to hold the address of the(freed) dynamic memory. After the delete, the pointer becomes what is referred to as a dangling pointer. A dangling pointer is one that refers to memory that once held an object but no longer does so.

Dangling pointers have all the programs of uninitialized pointers. We can avoid the problems with dangling pointers by deleting the memory associated with a pointer just before the pointer itself goes out of scope. That way there is no chance to use the pointer after the memory associated with the pointer is freed. If we need to keep the pointer around, we can assign nullptr to the pointer after we use delete. Doing so makes it clear that the pointer points to no object.

继续阅读