FAQ 12.11 How can an array of things be allocated and deallocated?

graphics/new_icon.gif

The best way is to be radical. Instead of trying to use an array pointer correctly, it is easier (and often more efficient) not to use explicit pointers at all but instead to use a container template such as vector (see FAQ 28.13). Please don't use explicit pointers unless it is necessary. Pointers are a source of a lot of errors; using a good container class library can eliminate many pointer errors.

If it is necessary or desired to use pointers anyway, the right way to allocate an array of things is with p = new Fred[n]. When the array is deallocated, the [] must appear just after the delete keyword, such as delete[] p;. Here is an example.

 class Fred { }; int main() {   Fred* p = new Fred[100];                           <-- 1   delete[] p;                                        <-- 2 } 

(1) Allocate an array of Fred

(2) [] is required when deallocating the array

The purpose of the syntactic difference between delete p and delete[] p is to distinguish deleting a thing from deleting an array of things. This is because there is no syntactic difference between the type "pointer to a thing" (Fred*) and the type "pointer to the first element of an array of things" (Fred*). This is a feature that C++ inherited from C.

After all this, recall that the real solution is to not use pointers at all but instead to use a good container class library. For example, when an array of things is needed, use a container class that implements an array of things, such as the standard template vector (see FAQ 28.13).



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