Wednesday, 18 April 2012

What is an auto pointer? | C++

When you allocate some memory to a variable and that variable becomes out of scope, then the deallocation of the memory can be done with the help of an auto pointer. This reduces the need of using the delete operator to deallocate memory. To use auto pointer, you can use the syntax
auto_ptr name (new type) and include the memory header file in which auto_ptr is defined. Let's understand the use of auto pointer with the help of the following code snippet:

#include <iostream.h>
 #include <memory.h>
 #include <string.h>
using namespace std;

int main(int argc, char **arv)
{
int *j = new int;
auto_ptr
m(j);
auto_ptr
n;
y = x;
cout<<m.get()<<endl;
cout<<n.get()<<endl;
}
In the preceding code snippet, the pointer j is deleted automatically by auto_ptr.

No comments: