To allocate objects in array, C++ compiler provides additional overload version of new and delete. The programs uses this special overload form to allocate array of objects. These overloaded form of new and delete use square brackets ( [ ] ) in syntax.
new <type> [ ]
MyType *mp = new MyType; //regular new
MyType *mp = new MyType[5]; //Invokes array new[]
The first form is regular new. This new shall allocate a single object and second form is special array overload. This will allocate array of 5 objects in this case.
delete [ ] <object>
C++ also has corresponding delete overloads. This special array delete make sure that memory allocated by array new is deallocated and all the objects are destroyed. The syntax of such delete is shown as follows:
delete np; //regular delete
delete [] np; //array version of delete[]
The first form shall destroy a single object, whereas, second form will destroy all the assigned array objects.
What is special about the special array overload
Both the normal new and new[ ] returns pointer to an object. Generally, both the pointers look very similar. However, the array overload internally stores additional meta information about the size of memory allocated. This information is stored in each created object. The C++ compiler understands by reading this meta information and then treats the given pointer as single object memory or set of memories.
However, it is the responsibility of the user to ensure that only array delete [ ] is used when array new [ ] created pointer.
If regular delete syntax is used to deallocate an array of objects then, it will give rise to memory leak.
#include <iostream> //main header
using namespace std; //namespace
class MainFunda
{
public:
MainFunda()
{
cout << "MainFunda()" << endl;
}
~MainFunda()
{
cout << "~MainFunda()" << endl;
}
};
int main()
{
MainFunda* a = new MainFunda[5];
delete a; //Wrong delete form used here
//delete [] a; //This is correct way
return 0;
}
This program allocates the memory for array of MainFunda objects of size 5. Therefore, the compiler calls its constructor 5 times. However, since the program calls a regular “delete” and not array delete [ ], it causes the destructor to be called only one time. Here, the compiler on seeing delete keyword “without array brackets [ ]” assumes that user knows what he is doing. Finally, the compiler will invoke the regular delete operator and deallocates only one object. This ultimately cause memory leak.
The output is:
MainFunda()
MainFunda()
MainFunda()
MainFunda()
MainFunda()
~MainFunda()
In above program, if we use “delete [ ] a” instead “delete a”, then the output looks as follows:
MainFunda()
MainFunda()
MainFunda()
MainFunda()
MainFunda()
~MainFunda()
~MainFunda()
~MainFunda()
~MainFunda()
~MainFunda()