adsense


Thursday, 26 November 2015

C++ LANGUAGE NEW AND DELETE OPERATORS

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE NEW AND DELETE OPERATORS






new and delete Operators 


There is following generic syntax to use new operator 
to allocate memory dynamically for any data-type.
 
new data-type; 

Here, data-type could be any built-in data type including 
an array or any user defined data types include class or 
structure. Let us start with built-in data types. For 
example we can define a pointer to type double and then 
request that the memory be allocated at execution time. 
We can do this using the new operator with the following statements: 

double* pvalue  = NULL; // Pointer initialized with null 

pvalue  = new double;   // Request memory for the variable 

The memory may not have been allocated successfully, if the 
free store had been used up. So it is good practice to check 
if new operator is returning NULL pointer and take appropriate 
action as below: 

double* pvalue  = NULL; 

if( !(pvalue  = new double )) 
32. DYNAMIC MEMORY 
{ 
   cout << "Error: out of memory." <<endl; 
   exit(1); 
 
} 
The malloc() function from C, still exists in C++, 
but it is recommended to avoid using malloc() function. 
The main advantage of new over malloc() is that new doesn't 
just allocate memory, it constructs objects which is prime 
purpose of C++. 

At any point, when you feel a variable that has been 
dynamically allocated is not anymore required, you 
can free up the memory that it occupies in the free 
store with the ‘delete’ operator as follows: 

delete pvalue;        // Release memory pointed to by pvalue 
Let us put above concepts and form the following 
example to show how ‘new’ and ‘delete’ work: 

#include <iostream> 
using namespace std; 
 
int main () 
{ 
   double* pvalue  = NULL; // Pointer initialized with null 
   pvalue  = new double;   // Request memory for the variable 
  
   *pvalue = 29494.99;     // Store value at allocated address 
   cout << "Value of pvalue : " << *pvalue << endl; 
 
   delete pvalue;         // free up the memory. 
 
   return 0; 
} 
If we compile and run above code, this would produce the following result: 
Value of pvalue : 29495 


No comments: