C++

C++ New Operator

We will cover how to efficiently manage allocation in C++ utilizing the ‘new’Β function through the use of practical examples.

In C++, the term “dynamic memory deployment” refers to the manual allotment of storage by a programmer. Heap is where distributed shared memory is deployed, while Stack is where non-static and local variables acquire memory resources.

Applications

  • Allocating storage of dynamic size, which is not achievable with compiler-allocated storage apart from varying arrays, is one usage of dynamic memory allocation.
  • The main benefit is the versatility it gives to programmers. We have absolute autonomy to allocate and release memory as needed and as no longer required. This versatility is useful in many situations.

How Does C++ Allocate and Deallocate Memory?

The malloc() and calloc() methods in C++ are used to dynamically change memory at execution. While the free() method is used to release the memory that has been allocated. These methods are provided by C++ together with the two ‘new’Β and ‘delete’Β operators that make memory allocation and release easier and more efficient.

The Correlation between the β€˜New’ Keyword and β€˜New’ Operator New

These two things are different from one another.

Two events take place: memory distribution and object formation. Both are handled by the ‘new’Β keyword. Calling the operator and calling the constructorΒ itself are the procedures to allocate storage. The operator ‘new’ willΒ not take any responsibility for invoking the constructor but it does let you adjust the storage allocation strategy. The new keyword has that responsibility. Calling the constructor without using operator new is feasible.

New Operator

Demand for memory allocation on the Open Storage is indicated by the new operator. If enough memory is accessible, a new operator processes data. Then, initializes it and gives the pointer object the address of the recently allocated and configured memory.

Example 1

We execute this code to show how the new and delete operators can be utilized; the memory will be dynamically allocated and released.

#include <iostream>
using namespace std;
int main ()
{
    int* a = NULL;
    a = new(nothrow) int;
    if (!a)
        cout << "Memory is not allocated\n";
    else
    {
        *a = 45;
        cout << "Value of a: " << *a << endl;
    }
    float *c = new float(67.84);
    cout << "Value of c: " << *c << endl;
    int x = 6;
    int *b = new(nothrow) int[x];

    if (!b)
        cout << "Memory is not allocated\n";
    else
    {
        for (int j = 0; j < x; j++)
            b[j] = j+1;

        cout << "A chunk of memory containing values: ";
        for (int j = 0; j < x; j++)
            cout << b[j] << " ";
    }
    delete a;
    delete c;
    delete[] b;
    return 0;
}

The required libraries <iostream>would be integrated. Next, the standard namespace will be added as β€˜std’. Here, the main() function would be invoked. We would initialize a pointer and set this pointer to β€˜NULL’. Let’s request storing the variables that are utilized for a β€˜new’ operator. The data type of β€˜a’ will be β€˜integer’. The β€˜if-else’ condition would apply. If the defined condition is satisfied, the β€˜cout’ statement will display the text β€˜Memory is not allocated’. Otherwise, we would store the value of the pointer.

Then, the β€˜cout’ command shows the value of the pointer. Now, we would request a block of memory by utilizing the β€˜new’ operator. We specify the floating-point value of the variable β€˜c’ by using the β€˜new’ operator. Now, the β€˜cout’ will print the value of variable β€˜c’. Here, we specify the size of the block of memory. We declare a variable β€˜x’ and set its data type as an β€˜integer’. We construct a new pointer named β€˜b’ and provide the value to it by using the β€˜new’ operator.

Once again, the β€˜if-else’ condition will be utilized. Within the β€˜else’ statement we have used the β€˜for’ statement. Initially, the loop variable β€˜j’ would be declared and we define the condition. Then, we increase the value of the loop variable by 1. The β€˜cout’ command would be used to print the line β€˜A chunk of memory containing values’. Once again, we will employ the β€˜for’ loop.

Now, we will free the allocated memory by the utilization of the β€˜delete’ operator.Β  Before adding the β€˜return 0’ command, we free the block of allocated memory by using the array.

We acquire this type of outcome after executing the above-mentioned program.

Example 2

In this instance, we will utilize the β€˜new’ operator for different objects.

#include <iostream>
#include <string>
using namespace std;  
int main()
 {
   int *l = NULL;
   l = new int();
   int *v = new int(23);
   if(!l)
   {
        cout<<"bad memory allocation"<<endl;
    }
   else
  {
       cout<<"memory allocated successfully"<<endl;
       *l = 20;
       cout<<"*l = "<<*l<<endl;
       cout<<"*v = "<<*v<<endl;
}  
double *arr = NULL;
arr = new double[20];
if(!arr)
 {cout<<"memory not allocated"<<endl;}
else
   {
     for(int k=0;k<20;k++)
       arr[k] = k+1;
       cout<<"arr values : ";
     for(int k=0;k<20;k++)
       cout<< arr[k]<<"\t";
   }
delete l;
delete v;
delete[] arr;  
return 0;
}

In the illustration is the integration of the necessary libraries <iostream>. Next, the namespace known as “std” will be added. The main() method would be called. To initialize a pointer, we would set it to “NULL.” The value of the variable “i” that is used for the “new” operator would be stored here. This variable’s data type is “integer.” The “if-else” condition will be utilized. If the specified condition is met, the text “Bad memory allocation” will be displayed by the “cout” statement. If not, we would keep the pointer’s value.

Then, the text “memory allocated successfully” is displayed using the “cout” command. The pointer’s value would be set. The value of the pointer would be displayed by the ‘cout’ command. We initialized the array with the data type “double” and gave it the value “NULL.” Using the ‘new’ operator, we define the value of this array. It uses an “if-else” statement. When the condition is met, the “cout” command prints “memory not allocated.”; else, we have used nested “for” statements.

Before defining the condition, the loop variable “j” would first be specified. Next, we add 1Β to the value of β€˜j’. The array’s values would be printed using the ‘cout’ command. We would use the “for” loop once again. Now, we will be using the delete operator. We will release the memory that was allocated. We release the block of allocated memory by utilizing the array before adding the “return 0” statement.

After implementing the aforementioned code, we get the desired result.

Conclusion

The usage ofΒ the ‘new’ operator is the focus of this article. For user-defined data types in classes and other data types, we will utilize the β€˜new’ operator. We have executedΒ two examples related to this topic. The first example demonstrates how to use C++’s β€˜new’ operator. The last illustration shows how to apply the “new” operator to objects.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.