TITLE: cleanup on exceptions in constructors (Newsgroups: comp.lang.c++.moderated, 4 Nov 96) JACEK: Jacek Jakob Surazski >> I realise that if an object throws an exception in the constructor, it's >> destructor won't be called. But what happens to the memory that was >> allocated to the object if it was created dynamically? >> >> t_object *object; >> try { >> object = new t_object(); >> } >> catch(...) >> { >> ... >> } HOWARD: walth@netcom.com (Walt Howard) > Yikes! You're right. However, and someone correct me if I'm >wrong, if you throw an exception in a constructor you still get >an object, it just has an aborted construction sequence and is >stillborn, so to speak. > > You just delete it like anything else, with a delete. > > However, what happens if the object is declared a local >variable, on the stack. What happens to MEMBERS of that object if >it's constructor is aborted by an exception? Are the members >automatically deleted? I'll have to code up an example and get >back to you. CLAMAGE: clamage@taumet.Eng.Sun.COM (Steve Clamage) If a constructor exits via an exception, the programmer cannot reliably tell how much was constructed or what needs to be destroyed. Consequently the compiler must take care of those details for you. The compiler ensures that each fully-constructed sub-object is destroyed (its destructor gets executed) as part of the exception process. In the case of dynamic allocation, the programmer can't tell whether the failure occurred before or after memory was allocated. The compiler must also take care of that case for you. If the constructor for t_object exits via an exception, the compiler generates code to invoke the version of "operator delete()" corresponding to the version of "operator new()" that was called. (The constructor would not have been called if "operator new()" had failed.) If you catch the exception, as in the example above, you can be sure all fully-constructed sub-objects have been destroyed, and if memory was allocated by "new" it has been deleted. The ARM did not specify what should happen in these cases, so exisiting compilers may vary. The draft standard addressed this hole in the C++ specification some time ago. Eventually all compilers should behave in this way.