1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
As we've seen operator tt(new) allocates the memory for an object and
subsequently initializes that object by calling one of its
constructors. Likewise, operator tt(delete) calls an object's destructor and
subsequently returns the memory allocated by operator tt(new) to the common
pool.
In the next section we'll encounter another use of tt(new), allowing us to
initialize objects in so-called emi(raw memory): memory merely consisting of
bytes that have been made available by either static or dynamic allocation.
Raw memory is made available by
hi(operator new) tt(operator new(sizeInBytes)) and also by tt(operator
new[](sizeInBytes)). The returned memory should not be interpreted as an array
of any kind but just a series of memory locations that were dynamically made
available. No initialization whatsoever is performed by these variants of
tt(new).
Both variants return tt(void *s) so (static) casts are required to use the
return values as memory of some type.
Here are two examples:
verb( // room for 5 ints:
int *ip = static_cast<int *>(operator new(5 * sizeof(int)));
// same as the previous example:
int *ip2 = static_cast<int *>(operator new[](5 * sizeof(int)));
// room for 5 strings:
string *sp = static_cast<string *>(operator new(5 * sizeof(string)));)
As tt(operator new) has no concept of data types the size of the intended
data type must be specified when allocating raw memory for a certain number of
objects of an intended type. The use of tt(operator new) therefore somewhat
resembles the use of ti(malloc).
The counterpart of tt(operator new) is ti(operator delete). tt(Operator
delete) (or, equivalently, tt(operator delete[])), expects a tt(void *) (so a
pointer to any type can be passed to it). The pointer is interpreted as a
pointer to raw memory which is returned to the common pool without any further
action. In particular, no destructors are called by tt(operator delete). The
use of tt(operator delete) therefore resembles the use of ti(free). To return
the memory pointed at by the abovementioned variables tt(ip) and tt(sp)
tt(operator delete) should be used:
verb( // delete raw memory allocated by operator new
operator delete(ip);
operator delete[](ip2);
operator delete(sp);)
|