The new[] operator in C++

The new[] operator is used to dynamically allocate a required amount of storage in the free store. The dynamically allocated memory has to be deleted properly and the delete operator is used for this purpose. Both of these operators are defined in the global namespace.

Using new[] operator:

The new[] operator can be used to work with any default and user-defined datatypes and classes. TheĀ  syntax for using new is as follows :

New datatypename[size], where the size in the subscript operator is equal to the number of objects of the specified datatype that the allocated space must store.

This operator also invokes the constructor of classes and default initialization for other datatypes.

When the memory allocation fails this operator throws an exception of type std::bad_alloc.

The following code illustrates the use of the new[] operator

#include <iostream>
class test
{
  int g{};
public:
  test()
  {
    std::cout << "constructor \n";
  }
  ~test()
  {
    std::cout << "destructor \n";
  }
  void setg(int h)
  {
    g = h;
  }
  int getg()
  {
    return g;
  }
};

int main()
{

  test* val = nullptr; //pointer  to store the dynamically allocated address
  val = new test[10]; //creates 10 test objects
  //using pointer arithmetic the acess the elements
  for (int i = 0; i < 10; i++)
  {
    (val + i)->setg(i);
  }
  for (int i = 0; i < 10; i++)
  {
    std::cout << (val + i)->getg() << " ";
  }


}
Output:
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
0 1 2 3 4 5 6 7 8 9

Conclusion:

Although the new[] operator might seem powerful, but it is always preferable to use a smart pointer to work with dynamically allocated memory. In this article, normal pointers are used to demonstrate pointer arithmetic which is not available in smart pointers. Every other thing remains the same.

Leave a Reply

Your email address will not be published. Required fields are marked *