Wednesday, February 02, 2011

Incorrect C++ compiler behavior in Visual Studio

As most C++ programmers know, an object that has been constructed via the new expression must be destroyed by calling delete. The delete-expression invokes the object’s destructor which in turn is responsible for clean up tasks. For instance, here’s some sample code that shows object creation, and then freeing it up via delete:

Foo *pF = new Foo();
// Do some work
delete pF;

The C++ Specification for delete has this to say:

The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.
delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression

The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void. (emphasis mine)

So, given that the delete expression has the return type void, what do you think the C++ compiler should do when it sees the following code:

Foo *pF = new Foo();
// Do some work
delete delete pF;

Read more: .NET Zone