To demand dynamic memory there is use the operators new. new is followed by a data type specifies and if a series of extra than a single element is mandatory- then there is use of brackets []. It returns a pointer to the beginning of the new block of memory allocated. |
|
Its syntax is: |
|
pointer = new type |
|
pointer = new type [elements] |
|
The initial expression is used to allow memory to hold a single element of type type. |
|
. The next one is used to allot a block (an array) of elements of type type, where elements are an integer value representing the number of these. |
|
For Example : |
|
int * john |
|
john = new int [ 5 ] |
|
|
|
John |
|
The initial element pointed by john can be accessed either with the look john[0] or the expression*john. Both are alike as has been explained in the section about pointers. |
|
The second element can be accessed either with john[1] or *(john+1) and so on… |
|
C++ provides two normal methods to make sure if the allotment was unbeaten: |
|
One is by management exceptions. By means of this technique an exception of type bad_alloc is thrown when the allotment fails. |
|
This exception method is the default method used by new, and is the one used in a pronouncement like: |
|
john =new int [15]; |
|
Another technique is recognized as nothrow, and what happens when it is used is that when a memory allotment fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution. |
|
This technique can be particular by using a unique object called nothrow as a parameter for new: |
|
john =new (nothrow)int [15]; |
|
Thus, if the allocation of this block of memory failed, the failure could be detected by checking if john took a null pointer value: |
|
int * john; |
|
john =new (nothrow)int [5 ] |
|
if (john == 0) { |
}; |
|
This nothrow method requires added work than the exception method. |
|
Operator Delete & delete [ ] |
|
In dynamic memory allocation there is allocation of memory at runtime. |
|
What happens if there is no need of object, then we can easily reallocate memory at run time with the help of delete and delete[] operator. |
|
As the requirement of dynamic memory is naturally limited to exact moments inside a program, once it is no longer wanted it should be untied so that the memory becomes accessible again for other needs of dynamic memory. |
|
Syntax of delete and delete[] operator is |
|
delete pointer; |
|
delete [] pointer; |