I reanimated my technical blog recently. During previous post research I came across this perfect page: C++ FAQ (http://www.parashift.com/c++-faq-lite)
Monday, June 23, 2008
Wednesday, June 18, 2008
Why does delete[] exist?
I would like to clarify the existence of special destruction operator for arrays, delete[] in C++.
Operator delete[] is used to destroy dynamically allocated arrays which are created using new[]. But why not have just one version of delete which determines on its own whether the object it is destroying is an array of objects or an individual. When we are allocating memory using new operator the system stores the size of the object in DWORD prior to the actual memory allocated for the object, and that information would be useful for deallocation.
Indeed, "The special destruction operator for arrays, delete[], isn't logically necessary. However, suppose the implementation of the free store had been required to hold sufficient information for every object to tell if it was an individual or an array. The user would have been relieved of the burden, but that obligation would have imposed significant time and space overheads on some C++ implementations."
The main problem that I see in case of incorrect usage of delete[] is that the destructor will not be called for all instances.
Let consider this:
class A
{
public:
A()
{
std::cout<<"Constructor"<<std::endl;
}
virtual ~A()
{
std::cout<<"Destructor"<<std::endl;
}
};
Here is results of my experiments with VS2005:
Example 1:
| int main() { A* p = new A[5]; delete []p; }; | Output Constructor Constructor Constructor Constructor Constructor Destructor Destructor Destructor Destructor Destructor Press any key to continue . . |
Example 2:
| int main() { A* p = new A[5]; delete p; }; | Output Constructor Constructor Constructor Constructor Constructor Destructor Press any key to continue . . |
In second example the destructor is called once only.
Actually this is not what we intended.
Good luck.
Tags: C++, memory leak
Thursday, June 12, 2008
C++09 new standard is intended to replace the existing C++ standard, ISO/IEC 14882
New standard of C++ is comming. It's intended to replace the existing C++ standard, ISO/IEC 14882, which was published in 1998. C++ Standards Committee aims to introduce the new standard in 2009. Draft is already available in Wikipedia, its called C++0x.
http://en.wikipedia.org/wiki/C++0x
Tags: C++
