new and delete

The new and delete operators respectively allocate and de-allocate memory. Given a pointer p1:
int *p1;
The following line allocates a new integer:
p1 = new int;
To deallocate the memory of such an integer, hence deleting the variable p1, we can write:
delete p1;
Once new is called it returns a pointer to the first byte of newly allocated memory. If such a piece of memory corresponds to a predefined type, the variable created in such a way might be initialized:
p1 = new int(72);
If the amount of available memory is lower than the amount requested a bad_alloc exception will be thrown. For this reason new statements should be inserted within try blocks, and any exceptions that might be thrown should be caught.

Example


#include <iostream>
#include <string>

using namespace std;

int main() 
{
    int *p1 = nullptr;
    int *p2 = nullptr;

    // You need a try-catch sequence if you want to
    // catch possible bad_alloc exceptions
    try 
    {
        // Allocates enough memory for an int and 
        // returns the address of the first byte
        p1 = new int;  
    }
    catch (const bad_alloc &except) 
    {
        cout << "p1's new has failed" << endl;
        return 1;
    }

    try 
    {
        // Allocates enough memory for an int, returns the 
        // address of the first byte and initializes it to 20
        p2 = new int(20);  
    }
    catch (const bad_alloc &except) 
    {
        cout << "p2's new has failed" << endl;
        return 1;
    }

    *p1 = 25; 
    cout << "*p1 is: " << *p1 << endl;
    cout << "*p2 is: " << *p2 << endl;

    delete p1;
    delete p2;
}

Output

*p1 is: 25
*p2 is: 20