I know that when delete [] will cause destruction for all array elements and then releases the memory.
I initially thought that compiler wants it just to call destructor for all elements in the array, but I have also a counter – argument for that which is:
Heap memory allocator must know the size of bytes allocated and using sizeof(Type) its possible to find no of elements and to call appropriate no of destructors for an array to prevent resource leaks.
So my assumption is correct or not and please clear my doubt on it.
So I am not getting the usage of [] in delete [] ?
Scott Meyers says in his Effective C++ book: Item 5: Use the same form in corresponding uses of new and delete.
Also, the memory allocator might allocate more space that required to store your objects and in this case dividing the size of the memory block returned by the size of each object won’t work.
Depending on the platform, the
_msize(windows),malloc_usable_size(linux) ormalloc_size(osx) functions will tell you the real length of the block that was allocated. This information can be exploited when designing growing containers.Another reason why it won’t work is that
Foo* foo = new Foo[10]callsoperator new[]to allocate the memory. Thendelete [] foo;callsoperator delete[]to deallocate the memory. As those operators can be overloaded, you have to adhere to the convention otherwisedelete foo;callsoperator deletewhich may have an incompatible implementation withoperator delete []. It’s a matter of semantics, not just keeping track of the number of allocated object to later issue the right number of destructor calls.See also:
EDIT: after having read @AndreyT comments, I dug into my copy of Stroustrup’s “The Design and Evolution of C++” and excerpted the following:
As @Marcus mentioned, the rational may have been “you don’t pay for what you don’t use”.
EDIT2:
In “The C++ Programming Language, 3rd edition”, §10.4.7, Bjarne Stroustrup writes: