new
operator allocates storage for a value.
new T
heap allocates a value of type T
.
new
T allocates a single value of type T.
new
operator can also allocate a block of values of type
T.
new T [n]
allocates a block of n
values of type T
.
n
may be zero, but it may not be negative.
new
operations can go wrong at run-time.
new
that returns a
null pointer on allocation error.
bad_alloc
exception.
#include// define exit-failure #include // define cee #include // define bad-alloc int main() { try { int * ip = new int [-10]; delete [] ip; } catch (std::bad_alloc ba) { std::cerr << "Allocation failed: " << ba.what() << "\n"; return EXIT_FAILURE; } }
#include// define exit-failure #include // define cerr #include // define nothrow int main() { int * ip = new(std::nothrow) int [100000000]; if (ip == 0) { std::cerr << "Allocation failed.\n"; return EXIT_FAILURE; } delete [] ip; }
main()
is not
freeing storage.
delete
operation returns the referenced storage chunk to the
heap.
delete []
operator.
This page last modified on 23 October 2003.