The new
and delete
operators allocate objects one at a time. Some applications, need the ability to allocate storage for many objects at once. For example, vector
s and string
s store their elements in contiguous memory and must allocate several elements at once whenever the container has to be reallocated (§ 9.4, p. 355).
To support such usage, the language and library provide two ways to allocate an array of objects at once. The language defines a second kind of new
expression that allocates and initializes an array of objects. The library includes a template class named allocator
that lets us separate allocation from initialization. For reasons we’ll explain in § 12.2.2 (p. 481), using an allocator
generally provides better performance and more flexible memory management.
Many, perhaps even most, applications have no direct need for dynamic arrays. When an application needs a varying number of objects, it is almost always easier, faster, and safer to do as we did with StrBlob:
use a vector
(or other library container). For reasons we’ll explain in § 13.6 (p. 531), the advantages of using a library container are even more pronounced under the new standard. Libraries that support the new standard tend to be dramatically faster than previous releases.
Most applications should use a library container rather than dynamically allocated arrays. Using a container is easier, less likely to contain memory-management bugs, and is likely to give better performance.
As we’ve seen, classes that use the containers can use the default versions of the operations for copy, assignment, and destruction (§ 7.1.5, p. 267). Classes that allocate dynamic arrays must define their own versions of these operations to manage the associated memory when objects are copied, assigned, and destroyed.