6

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?

Mateen Ulhaq
  • 18,406
  • 13
  • 75
  • 112
HS.
  • 2,505
  • 2
  • 20
  • 28

5 Answers5

27

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.

Martin York
  • 234,851
  • 74
  • 306
  • 532
Andreas Magnusson
  • 7,103
  • 3
  • 29
  • 36
4

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.

CAdaker
  • 12,581
  • 3
  • 27
  • 30
2

Just because they might work the same now, doesn't mean you can necessarily treat them the same - the behaviour could change. And besides, who cares - you should write your code so you don't have to remember.

Additionally, you can use scoped_array for array deletion.

1800 INFORMATION
  • 119,313
  • 29
  • 152
  • 234
2

Perhaps the data you deleted did not have destructors? If so, this simple delete would make sense. It is working on void* after all.

Anyway, you're supposed to use delete[] to make sure that the destructor is run for each element in the array.

Jørn Jensen
  • 898
  • 1
  • 10
  • 16
2

Deleting an array without [] will only free the memory, but will NOT call the destructors in each object in the array. So, technically you only need [] if your destructor needs to be called.

Magnus Westin
  • 879
  • 7
  • 12