Free Store

Free store is used for dynamic allocation of memory. The new and delete operators are used to allocate and deallocate free store, respectively. You can define your own versions of new and delete for a class by overloading them. You can supply the new and delete operators with additional arguments. You can also use the /Tm option to enable the debug versions of these operators. See Debug Versions of new and delete for more information on these versions. When new and delete operate on class objects , the class member operator functions new and delete are called, if they have been declared.

If you create a class object with the new operator, the operator function operator new() (if it has been declared ) is called to create the object. An operator new() for a class is always a static class member, even if it is not declared with the keyword static . It has a return type void* and its first argument must be the size of the object type and have type size_t. It cannot be virtual.

Type size _t is an implementation dependent unsigned integral type defined in <stddef.h>.

When you overload the new operator, you must declare it as a class member , returning type void*, with first argument size_t, as described above. You supply additional arguments in the declaration of operator new(). Use the placement syntax to specify values for these arguments in an allocation expression.

The delete operator destroys an object created by the new operator. The operand of delete must be a pointer returned by new. If delete is called for an object with a destructor, the destructor is invoked before the object is deallocated.

If you destroy a class object with the delete operator, the operator function operator delete() (if it has been declared) is called to destroy the object. An operator delete() for a class is always a static member, even if it is not declared with the keyword static. Its first argument must have type void*. Because operator delete() has a return type void, it cannot return a value. It cannot be virtual.

When you overload the delete operator, you must declare it as class member, returning type void, with first argument having type void*, as described above. You can add a second argument of type size_t to the declaration. You can only have one operator delete() for a single class.

The result of trying to access a deleted object is undefined because the value of the object can change after deletion.

If new and delete are called for a class object that does not declare the operator functions new and delete, or they are called for a nonclass object, the global operators new and delete are used. The global operators new and delete are provided in the C++ library. The IBM C and C++ Compilers does not support them. When you declare arrays of class objects, the global new and delete operators are used.



Examples of operator new() and operator delete()


new Operator
delete Operator
Overloaded new and delete