operator new
The solution in C++ is to combine all the
actions necessary to create an object into a single operator called
new. When you create an
object with new (using a
new-expression), it
allocates enough storage on the heap to hold the object and calls the
constructor for that storage. Thus, if you say
MyType *fp = new MyType(1,2);
at runtime, the equivalent of
malloc(sizeof(MyType)) is called (often, it is literally a call to
malloc( )), and the constructor for
MyType is called with the resulting address as the this
pointer, using (1,2) as the argument list. By the
time the pointer is assigned to fp, it’s a live, initialized object
– you can’t even get your hands on it before then. It’s also
automatically the proper MyType type so no cast
is necessary.
The default new checks to make
sure the memory allocation was successful before passing the address to the
constructor, so you don’t have to explicitly determine if the call was
successful. Later in the chapter you’ll find out what happens if
there’s no memory left.
You can create a new-expression using any
constructor available for the class. If the constructor has no arguments, you
write the new-expression without the constructor argument list:
MyType *fp = new MyType;
Notice how simple the process of creating
objects on the heap becomes – a single expression, with all the sizing,
conversions, and safety checks built in. It’s as easy to create an object
on the heap as it is on the
stack.