overloading was done for efficiency, it may be that for arrays the default operator is the most efficient.

Example

#include <iostream.h> class C {

public:

void* operator

new[ ]

(size_t);

// new for arrays

void operator delete[

] (void*);

// delete for arrays

// additional

class details omitted

};

void* C::operator new[ ] (size_t allocSize)

{

cout << “Use operator new[ ] from class C\n”;

// here, real usage would include allocation

return ::operator new[ ] (allocSize); // global operator

}// for this simple // example

void C::operator delete[ ] (void *p)

{

cout << “Use operator delete[ ] from class C\n”;

// here, real usage would include deallocation

::operator delete[ ] (p);

// global operator

}

// for this simple

 

// example

int main()

 

{

 

C *p;

 

p = new C[10];

 

delete[ ] p;

 

}

 

Notice that the new operator takes a class with an array specifier as an argument. The compiler uses the class and array dimension to provide the size_t argument. In the example above, the argument provided is ten times the size of a class C object. Also, the operator must return a void* which the compiler converts to the class type. The void constructor for the class (if one exists) is invoked to initialize the elements in the array.

Multidimensional arrays can be allocated and deallocated with these operators. The operator is used with several array dimensions, and the compiler provides the size_t argument which is the space required for the entire array. For example:

//call C::operator new[ ] ( ) with

//an argument of 10 * 20 * sizeof(C)

p = new C [10] [20];

Additional arguments can be provided to this operator new just as for the operator for single objects. In this way, the operator can be overloaded in a class. The additional arguments can be used by the storage allocation scheme for additional storage management.

The global new and delete for both arrays and single objects are provided in the Standard C++ Library. This library also provides a version of new for arrays and single objects that takes a second void* argument and constructs the object at that address.

Overloading new[] and delete[] for Arrays 151

Page 151
Image 151
HP C/aC++ for PA-RISC Software manual Example