Well, at least in the case of VC++, there will be no memory leaked by forgetting the [] when you call delete to free up an array of ints. But I would code it with the [] for consistency with the cases that do require it.
You see, the call
int *pData = new int[nWidth];
leads to
- the allocation of a single block of nWidth * sizeof(int) bytes (big enough for all elements)
- the default constructor being called on each element (which doesn't do a lot, as it's an int)
delete [] pData;
results in
- the destructor being called on each element (which doesn't do anything...)
- the (single) block being freed
If you forget the [], the destructor is only called on the first element. But the single block is still freed, so the base memory is handled OK. As the int destructor does nothing, there's no real difference (as far as memory goes)
But leaks will happen if the element is a class that allocates dynamic memory or some other resource. The bottom line is that you should always use the [] out of habit, so you never forget it when it's needed!
Notes
1. built in types don't really have a constructor or destructor, but they behave as if they do. See "Do built-in types have default constructors?"
http://stackoverflow.com/questions/5113365/do-built-in-types-have-default-constructors
2. Other compilers might do something different, but allocating a single block to hold all the elements is going to be a pretty common approach given the way memory is managed (remember, new must allocate the array elements in contiguous memory)
3. Illustration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
using namespace std;
class Demo {
private:
int m_value;
public:
Demo() : m_value(0) {
cout << "Demo::Demo()" << endl;
}
~Demo() {
cout << "Demo::~Demo()" << endl;
}
};
int main() {
const int nWidth = 3;
Demo *pDemo = new Demo[nWidth];
cout << endl;
delete pDemo;
cout << endl;
return 0;
}
|
Demo::Demo()
Demo::Demo()
Demo::Demo()
Demo::~Demo() |
Only one, lone delete!
Andy
PS In real code I would use a std::vector<> instead.