TITLE: throwing pointers (Newsgroups: comp.lang.c++.moderated, 13 Feb 98) CLAMAGE: Steve Clamage >> There is nothing intrinsically wrong with throwing a pointer. In >> your example, the exception object is created on the heap. Suppose >> you threw the object, instead of throwing a pointer to it. The heap >> object would be copied for the throw, (wasteful) and you would have >> no way to delete the original (resource leak). >> >> But in the example, the object is created on the heap, and a copy >> of a pointer is thrown. The pointer is copied yet again when it is >> caught. We don't usually worry about (or even think about) needing >> to copy pointers or other simple types, because there is usually no >> cost. MENZI: Gerhard Menzl > The problem I see with throwing pointers is that the catcher cannot > possibly know whether it should delete the object pointed to. CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) But isn't that always a potential problem with pointers, in any context? If you create a heap object, you need an ownership policy that defines who is responsible for deleting it. Three example policies for this case: 1. The exception object is small and simple; the destructor does nothing. Assuming the exception rarely occurs, you simply ignore the possibility of a memory leak, and never worry about deleting an exception object. This policy is often quite reasonable, despite my comments above, where I was speaking more generally. 2. The exception object is always created on the heap. A catch clause either re-throws the pointer or deletes the exception object. You can help enforce the "only on the heap" policy by providing only private constructors, and a public static member function that creates the object on the heap. 3. The exception object is never created on the heap, and thus is never deleted. You can help enforce both aspects of the policy by declaring and not implementing private member operators new and delete.