Export (0) Print
Expand All
Expand Minimize
This topic has not yet been rated - Rate this topic

operator new

Allocates block of memory from heap

void *__cdecl operator new(
   size_t count
);
void *__cdecl operator new(
   size_t count, 
   void * object
) throw();
void *__cdecl operator new(
   size_t count, 
   const std::nothrow_t&
) throw();

Parameters

count
The size of the allocation.
object
A pointer to a block of memory in which the object will be created.

Return Value

A pointer to the lowest byte address of the newly allocated storage.

Remarks

This form of operator new is known as scalar new, in contrast to the vector new form (operator new[]).

The first form of this operator is known as the nonplacement form. The second form of this operator is known as the placement form and the third form of this operator is the nonthrowing, placement form.

The first form of the operator is defined by the compiler and does not require new.h to be included in your program.

operator delete frees memory allocated with operator new.

You can configure whether operator new returns null or throws an exception on failure. See The new and delete Operators for more information.

With the exception of throwing or no-throwing behavior, the CRT operator new behaves like operator new in the Standard C++ Library.

Requirements

Routine Required header Compatibility
new <new.h> Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.

Libraries

All versions of the C run-time libraries.

Example

The following shows how to use the scalar, nonplacement form of operator new.

// crt_new1.cpp
#include <stdio.h>
int main() {
   int * i = new int(6);
   printf("%d\n", *i);
   delete i;
}

The following shows how to use the scalar, placement form of operator new.

// crt_new2.cpp
#include <stdio.h>
#include <new.h>
int main() {
   int * i = new int(12);
   printf("*i = %d\n", *i);
   // initialize existing memory (i) with, in this case, int(7)
   int * j = new(i) int(7);   // placement new
   printf("*j = %d\n", *j);
   printf("*i = %d\n", *i);
   delete i;   // or, could have deleted j
}

The following shows how to use the scalar, placement, no-throw form of operator new.

// crt_new3.cpp
#include <stdio.h>
#include <new.h>
int main() {
   // allocates memory, initialize (8) and if call fails, new returns null
   int * k = new(std::nothrow) int(8);   // placement new
   printf("%d\n", *k);
   delete k;
}

See also

Memory allocation | Run-Time Routines and .NET Framework Equivalents

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.