C++ and STL
  Common Issues
  Destructor
  regex
  string
 MFC
  CButton
  CDialog
  CEdit
  CInternetSession
  CWinThread
  CWnd
 MS VS FAQ
  Compiling, building
  Debugging
  Editor
  Settings
 Win32, API
  Console
  File System
  Graphics
  Internet functions
  Kernel objects
  Security
  Sound
  Thread, process
  Window
 Windows NT/2K*
  Logon, logoff...
  Networking
  Service Packs
 | About
  About
  Links & Freeware

Powered by
CoderTown



delete and arrays

Usually it is possible to use delete for deleting an array by the following:

   char* pArray = new char[100];
   //...
   delete pArray;

But this is only true if this array defined to be an array of any standard type like 'int', 'char' etc. If type of objects in the array is not standard you will have problems: at the point of deleting the array, destructor for only the first object in the array will be called. Now you can consider the potential risk of memory leak in your application. To deallocate memory properly you need to do it like this:

   delete [] pArray;

That guarantees that every single desctructor will be called.

Resume: to avoid confuse keep certain style for using of delete:

   delete pObject;          // Delete one object like one 'char'
   delete [] pArray;        // Delete an array

Update:

Here we can see behaviour of applying operator delete to an array only in MS Visual C++ Compilers. But in general - behavious is undefined (UB). Other compilers can produce other behaviour:

Standard C++03, 5.3.5/2:
the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.

Therefore, in order to avoid problems, you must always use new/delete, new[]/delete[], or (what is better) std::vector/std::auto_ptr/boost::shared_ptr etc.

Created: 2003-05-12
Updated: 2006-02-09

Google
 
Web visualcpp.net
msdn.microsoft.com codeguru.com