How new Works

The allocation-expression — the expression containing the new operator — does three things:

The new operator invokes the function operator new. For arrays of any type, and for objects that are not of class, struct, or union types, a global function, ::operator new, is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.

When the compiler encounters the new operator to allocate an object of type type, it issues a call to type::operator new( sizeof( type ) ) or, if no user-defined operator new is defined, ::operator new( sizeof( type ) ). Therefore, the new operator can allocate the correct amount of memory for the object.

Note   The argument to operator new is of type size_t. This type is defined in DIRECT.H, MALLOC.H, MEMORY.H, SEARCH.H, STDDEF.H, STDIO.H, STDLIB.H, STRING.H, and TIME.H.

An option in the syntax allows specification of placement (see Syntax for new Operator). The placement parameters can be used only for user-defined implementations of operator new; it allows extra information to be passed to operator new. An expression with a placement field such as

T *TObject = new ( 0x0040 ) T;

is translated to

T *TObject = T::operator new( sizeof( T ), 0x0040 );

The original intention of the placement field was to allow hardware-dependent objects to be allocated at user-specified addresses.

Note   Although the preceding example shows only one argument in the placement field, there is no restriction on how many extra arguments can be passed to operator new this way.

Even when operator new has been defined for a class type, the global operator can be used by using the form of this example:

T *TObject =::new TObject;

The scope-resolution operator (::) forces use of the global new operator.