I know that I am supposed to use delete []
after I use new []
, so using auto_ptr
with new []
is not such a bright idea.
However, while debugging delete []
(using Visual Studio 2005), I noticed that the call went into a function that looked like this:
void operator delete[]( void * p )
{
RTCCALLBACK(_RTC_Free_hook, (p, 0))
operator delete(p);
}
Does this mean, the []
syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?
Consider this code:
class DeleteMe
{
public:
~DeleteMe()
{
std::cout << "Thanks mate, I'm gone!\n";
}
};
int main()
{
DeleteMe *arr = new DeleteMe[5];
delete arr;
return 0;
}
If you run that in VS2005 it will print:
Thanks mate, I'm gone!
If you change main()
to correctly adhere to the C++ standard:
int main()
{
DeleteMe *arr = new DeleteMe[5];
delete[] arr;
return 0;
}
It will print:
Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone! Thanks mate, I'm gone!
Don't shoot yourself in the foot. VS2005 will NOT do the correct thing if you mismatch different flavors of new/delete. Neither will any other C++ standard conformant compiler.
There's some compiler magic going on around operator new
and operator delete
(and their different flavors), basically the call to the ctors and dtors are added behind the scenes. This magic depends on those small brackets [], so don't lose them or you'll lose the magic.
I guess it's just an implementation detail. Their heap allocator works the same way when freeing arrays and pointers.
But since the standard allows implementations to have different algorithms for the two cases, you really shouldn't assume that delete
and delete[]
do the same thing. The behaviour might even change between compiler versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With