2.1 Storage Management
C++ defines two functions for storage management,
new (for storage allocation)
delete(for de-allocation).
The syntax for new is
pointer = new <type> or
pointer = new <type> [<size>]
- new returns a pointer.
- Example:
int *pi = new int; // a pointer to a new int
Rational *p1 = new Rational; // a pointer to a new Rational
Rational *p2 = new Rational[10]; // a pointer to an array of 10 Rationals
Rational *p3 = new Rational(3,4); // pointer to new initialized Rational
QUESTION:
What advantage(s) does new have over malloc or calloc?
ANSWER:
- De-allocation of storage is done by the function delete.
The syntax for delete is
delete <object> or
delete [] <object>
- For example:
delete pi; // deletes the single int pointed to by pi
delete [] p2; // deletes the entire array of Rationals
The private getBuffer function called by the constructors
inline void String::getBuffer(const unsigned int Max_Length)
{
Buffer_Len = Max_Length + 1;
Buffer = new char [ Buffer_Len ];
if( !Buffer )
Error( "Out of space" );
}
- The function Error is not defined. You must write it.