Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete and delete [] the same in Visual C++?

Tags:

c++

visual-c++

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?

like image 441
HS. Avatar asked Nov 19 '08 09:11

HS.


2 Answers

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.

like image 119
Andreas Magnusson Avatar answered Sep 20 '22 17:09

Andreas Magnusson


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.

like image 40
CAdaker Avatar answered Sep 17 '22 17:09

CAdaker