C++ New Library - operator new[]


Advertisements

Description

It allocates storage space for array.

Declaration

Following is the declaration for operator new[].

	
void* operator new[] (std::size_t size) throw (std::bad_alloc);   (throwing allocation)
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) throw();   (nothrow allocation)
void* operator new[] (std::size_t size, void* ptr) throw();   (placement)

C++11

	
void* operator new[] (std::size_t size);    (throwing allocation)
void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;	(nothrow allocation)
void* operator new[] (std::size_t size, void* ptr) noexcept;    (placement)

Parameters

  • size − It contain size in bytes of the requested memory block.

  • nothrow_value − It contains the constant nothrow.

  • ptr − It is a pointer to an already-allocated memory block of the proper size.

Return Value

It returns a pointer to the newly allocated storage space.

Exceptions

If it fails to allocate storage then it throws bad_alloc.

Data races

It modifies the storage referenced by the returned value.

Example

In below example explains about new operator.

#include <iostream>
#include <new>

struct MyClass {
   int data;
   MyClass() {std::cout << '@';}
};

int main () {
   std::cout << "constructions (1): ";
   MyClass * p1 = new MyClass[10];
   std::cout << '\n';

   std::cout << "constructions (2): ";
   MyClass * p2 = new (std::nothrow) MyClass[5];
   std::cout << '\n';

   delete[] p2;
   delete[] p1;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

constructions (1): @@@@@@@@@@
constructions (2): @@@@@
new.htm
Advertisements