CAUTION: MANAGING DYNAMIC MEMORY IS ERROR-PRONE
The following three common program errors are associated with dynamic memory allocation:
1. Failing to delete a pointer to dynamically allocated memory, thus preventing the memory from being returned to the free store. Failure to delete dynamically allocated memory is spoken of as a “memory leak.” Testing for memory leaks is difficult because they often do not appear until the application is run for a test period long enough to actually exhaust memory.
2. Reading or writing to the object after it has been deleted. This error can sometimes be detected by setting the pointer to 0 after deleting the object to which the pointer had pointed.
3. Applying a delete expression to the same memory location 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 be corrupted.
These kinds of errors in manipulating dynamically allocated memory are considerably easier to make than they are to track down and fix.
这一段值得反复阅读,它指出了C++(www.cppentry.com) 中使用new/delete 手动管理内存的常见错误:内存泄漏、空悬指针、双重释放。对此, 现代C++(www.cppentry.com) 语言有一套完整的解决办法,即使用STL 容器及智能指针来自动管理内存。
Deleting a const Object
Although the value of a const object cannot be modified, the object itself can be destroyed. As with any other dynamic object, a const dynamic object is freed by deleting a pointer that points to it:
delete pci; // ok: deletes a const object
Even though the operand of the delete expression is a pointer to const int, the delete expression is valid and causes the memory to which pci refers to be deallocated.
EXERCISES SECTION 5.11
Exercise 5.30: Which of the following, if any, are illegal or in error
(a) vector<string> svec(10);
(b) vector<string> *pvec1 = new vector<string>(10);
(c) vector<string> **pvec2 = new vector<string>[10];
(d) vector<string> *pv1 = &svec;
(e) vector<string> *pv2 = pvec1;
(f) delete svec;
(g) delete pvec1;
(h) delete [] pvec2;
(i) delete pv1;
(j) delete pv2;