Josef “Jeff” Sipek

Awful, Awful C++: Exceptions & the new operator

Over the past few months, I have pondered many aspects of C++. I thought it would be good to write my concerns and conclusions down somewhere. That somewhere ended up being right here — my blahg.

I was thinking about C++ and how quirky it is. And then I considered the scenario where you dynamically allocate an object, but the constructor throws an exception. Would that free the allocated object? Well, section 14.4.4 in the C++ book answers that:

What happens if X’s constructor throws an exception? Is the memory allocated by the operator new() freed? For the ordinary case, the answer is yes…

When the placement syntax is used, the answer cannot be that simple. Some uses of that syntax allocate memory, which then ought to be released; however, some don’t. Furthermore, the point of using the placement syntax is to achieve nonstandard allocation, so nonstandard freeing is typically required. Consequently, the action taken depends on the allocator used. If an allocator Z::operator new() is used, Z::operator delete() is invoked if it exists; otherwise, no deallocation is attempted.

Curse you, Bjork Stroustrup!


  1. But...his name isn't...oh I see what you did there.

    Comment by obiwan — January 13, 2011 @ 02:33

Atom feed for comments on this post.

Leave a comment

Powered by blahgd