Monday, April 19, 2010

new operator in C++

Allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.
[::] new [placement] new-type-name [new-initializer]
[::] new [placement] ( type-name ) [new-initializer]
If unsuccessful, new returns zero or throws an exception.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
Use the delete operator to deallocate the memory allocated with the new operator.

The following example allocates and then frees a two-dimensional array of characters of size dim by 10. When allocating a multidimensional array, all dimensions except the first must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. When allocating an array using the new operator, the first dimension can be zero — the new operator returns a unique pointer.
char (*pchar)[10] = new char[dim][10];
delete [] pchar;

The type-name cannot contain const, volatile, class declarations, or enumeration declarations. The new operator does not allocate reference types. The new operator cannot be used to allocate a function, but it can be used to allocate pointers to functions.

No comments:

Post a Comment