C++ new and delete Operators

Introduction

We can dynamically allocate and deallocate storage for our object and have pointers point to this newly allocated memory.

The operator new allocates space for an object.

The allocated memory must be deallocated using operator delete.

It deallocates the memory previously allocated memory with an operator new.

Example:

#include <iostream> 

int main() //from  www .  j a v a 2 s  . co  m
{ 
    int* p = new int; 
    *p = 123; 
    std::cout << "The pointed-to value is: " << *p; 
    delete p; 
} 

This example allocates space for one integer on the free-store.

Pointer p now points to the newly allocated memory for our integer.

We can now assign a value to our newly allocated integer object by dereferencing a pointer.

Finally, we free the memory by calling the operator delete.

If we want to allocate memory for an array, we use the operator new[].

To deallocate a memory allocated for an array, we use the operator delete[].

Pointers and arrays are similar and can often be used interchangeably.

Pointers can be dereferenced by a subscript operator [].

Example:

#include <iostream> 

int main() /*from   w  w  w . jav a 2s  . c o  m*/
{ 
    int* p = new int[3]; 
    p[0] = 1; 
    p[1] = 2; 
    p[2] = 3; 
    std::cout << "The values are: " << p[0] << ' ' << p[1] << ' ' << p[2]; 
    delete[] p; 
} 

This example allocates space for three integers, an array of three integers using operator new[].

Our pointer p now points at the first element in the array.

Then, using a subscript operator [], we dereference and assign a value to each array element.

Finally, we deallocate the memory using the operator delete[].

Always delete what you new-ed and always delete[] what you new[]-ed.

We prefer smart pointers to operator new.

The lifetime of objects allocated on the free-store is not bound by a scope in which the objects were defined.

We manually allocate and manually deallocate the memory for our object, thus controlling when the object gets created and when it gets destroyed.




PreviousNext

Related