How new Works

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

  • Locates and reserves storage for the object or objects to be allocated. When this stage is complete, the correct amount of storage is allocated, but it is not yet an object.

  • Initializes the object(s). Once initialization is complete, enough information is present for the allocated storage to be an object.

  • Returns a pointer to the object(s) of a pointer type derived from new-type-name or type-name. The program uses this pointer to access the newly allocated object.

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 grammar allows specification of placement (see the Grammar for new Operator). The placement parameter 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 ); if class T has member operator new, otherwise to T *TObject = ::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.

See Also

Reference

new Operator (C+)