FAQ 12.13 Can the of delete p be dropped when p points to an array of some built-in type such as char ?

FAQ 12.13 Can the [] of delete[] p be dropped when p points to an array of some built-in type such as char?

No; there is no reason to do this and it risks an avoidable disaster.

Some programmers tragically think that the [] in the delete[] p exists only so that the compiler will call the appropriate number of destructors. Following this reasoning, they assume that the [] are optional when the array is of some built-in type such as an array of char:

 #include <new> using namespace std; void sample(int n) throw(bad_alloc) {   char* p = new char[n];   // ...   delete p;                                          <-- 1 } int main() { sample(10); } 

(1) ERROR! Should be delete[] p;

The delete p; line above is wrong, and it can cause a disaster at runtime. In particular, the underlying deallocation primitive called for delete p; is operator delete(void*), but the deallocation primitive called for delete[] p; is operator delete[](void*). The default behavior for the latter is to call the former, but users are allowed to replace the latter with a different behavior. For example, someone might replace operator new[](size_t) (the allocation primitive called for new char[n]) and operator delete[](void*) with a separate heap from operator new(size_t) and operator delete(void*). If that happens, the delete p; line sends the pointer to the wrong heap, which could result in a disaster at runtime.

Remember: use container classes rather than raw pointers. This example could use the standard string class or perhaps something like the standard vector template.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net