delete and delete [] what is the difference
-
If you allocate an array with new, you use
delete []
when you free the memory. --Mike-- http://home.inreach.com/mdunn/ This must be Thursday. I never could get the hang of Thursdays... -
If you allocate an array with new, you use
delete []
when you free the memory. --Mike-- http://home.inreach.com/mdunn/ This must be Thursday. I never could get the hang of Thursdays...But delete and delete[] both seem to generate the same assembly output, so is there really a difference ? :confused:
-
But delete and delete[] both seem to generate the same assembly output, so is there really a difference ? :confused:
They may look the same, but they're not. For instance, take this simple application:
#include "stdafx.h"
#include
using namespace std;
class a
{
public:
a(){};
~a(){cout << "a::~a()\n";};
};int main(int argc, char* argv[])
{
a *pa = new a[10];
delete [] pa;
cout << "------" << endl;
pa = new a[10];
delete pa;return 0;
}
If your theory were correct, it would output 10 a::~a()'s followed by dashes and 10 more. Instead, this is the output:
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()
a::~a()a::~a()
As you can see, the destructor gets called 10 times when using delete [] and only once when using delete.
-
But delete and delete[] both seem to generate the same assembly output, so is there really a difference ? :confused:
Delete[] is necessary for deletion of objects. I mean instances of classes. Objects in array should be garanteed to destruct itself and free resource. Delete[] calls all of destructor of objects in array and call of destructor calls destructor of base class's destructor. So delete[] gaurantees destruction of all object in array . For primitive types like int, long, char etc.. You don't have use delete[] for freeing resource. Delete is enough. But this is only the theory.. In practice,I recommend to use delete[] whenever you're freeing resource in array. Cause it makes code more clear and readable. It looks to clear to other developers who are seeing your code or youself in future. Regards, Ryan