# Let a class instance delete itself (at errors)

This topic is 4376 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was wondering if this is possible (and how): I have a class CL, which I make an instance of: CL* instance = NULL; I now initialize this instance, by calling a second line: instance = new CL(argumentslist); This triggers the constructor, which itself triggers some boolean function which has to return a true value, else some termination function (NOT the destructor, the destructor itself needs more code than just this termination function because if the initialization DOES go right more stuff is done that needs to be undone in the destructor) is called. In this function I free all memory again to prevent leaks. But one thing's missing. If the initialization fails, this doesn't work: if (!instance) return 0; The instance still exists (guess because I didn't call the constructor :)). Is there a way I can destroy the instance totally from within if initialization fails? Thanks a lot in advance!

##### Share on other sites
Throw an exception?

Edit: oh, from within: no not really

##### Share on other sites
Throwing an exception is The Right Thing To Do. Then your destructor will be called, and you can clean up there. If your destructor is not capable of cleaning up from a failed constructor, then you should fix that.

##### Share on other sites
Quote:
 Original post by SubotronIs there a way I can destroy the instance totally from within if initialization fails?

You could do "delete this" ... lol, but, that's not always a wise thing to do...

As a simple workaround for your problem, try doing something like this:
CL* instance = new CL(arguments);if(instance->initialize() == false){    delete instance;    instance = null;}else{    // continue on normally...}

Where initialize() is that boolean function you're calling from within the constructor.

##### Share on other sites
Thanks a lot, but could you please tell me how to do this?

edit: omega, that would work, but I really want the boolean function to be called from within the constructor, instead of seperately.

##### Share on other sites
You should wrap your costructor code in try {} and throw execeptions when anythings goes wrong, releasing the resources in the catch() {} block and throwing the same or another exception.
Of course, this requires exception-safe code. [smile]

##### Share on other sites
Quote:
 Throwing an exception is The Right Thing To Do. Then your destructor will be called,

However, an exception thrown from a constructor will not invoke the destructor of said object (an object that is not constructed should not be destructed, and an object is not constructed until the successful completion of its constructor). Thus if a constructor has already done something that should be cleaned up when an exception must be thrown, than the cleanup must occur then (this is why the RAII idiom is useful).

Consider: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.4

And to the OP: look up the "resource acquision is initialization" idiom. It is legal to, f.e.x., perform a "delete this" within a member function of an object, but its dangerous and you need to be sure you know what you are doing. It is not the proper solution to your problem.

##### Share on other sites
Side question here... In MSVC 2003, there's an option under Project->Properties->C/C++->Code Generation->Enable C++ Exceptions ... Is this required to be on in order to have exceptions in the code? I haven't done much with exceptions since VC++ 6.

##### Share on other sites
Er, yes. Brain fart. I was thinking of delete being called, not the destructor being called. Thanks for the correction.

##### Share on other sites
ok, guess I have to put in a different question:

suppose at some point in my constructor something fails (the initialization function returns false), can I then call the destructor from within the constructor?

Like this:
class::class(){    if (!initialize)        Call_destructor_here();}

##### Share on other sites
Quote:
 Original post by Subotronok, guess I have to put in a different question:suppose at some point in my constructor something fails (the initialization function returns false), can I then call the destructor from within the constructor?Like this:class::class(){ if (!initialize) Call_destructor_here();}

Will the compiler allow you to do this? Yes.

Should you do this? God no.

Since a constructor cannot return a value to indicate failure, you do not allow the classes clients to know there was a failure, so they will use an invalid object as if it was valid. Better to cleanup and throw an exception.

It is rare that you need to call a destructor explicitly. It is even rarer for such code not to have an alternate that is simpler. (eg, moving common cleanup to another function, and adding a member variable to indicate whether the class is initialised properly...

Edit: also remember that if you call a destructor explicitly, the destuctor will be called again when delete is used, or when a stack object goes out of scope. Your destructor must be capable of being called twice.

##### Share on other sites
Just to expand on what I was (incorrectly) talking about before: If you throw an exception from the constructor, the destructor won't be called, but the memory WILL be freed. So even in that case, resources are not leaked.

##### Share on other sites
It's possible to manually invoke a destructor. But you shouldn't do it, especially not in your specific situation. There is a reason that the destructor is not automatically called when a constructor fails (and throws) -- don't try to circumvent this!

Your object has not been fully constructed; therefore it is possible that the destructor could fail, or do something else naughty like clean up a resource that hasn't been allocated yet. Double deletes are preventable but not all kinds of release are. You are just displacing your problem, and in fact making it harder for yourself (you can't throw an exception from a destructor or the runtime will shoot your application dead).

Employ the RAII idiom in your constructors. Be careful that your write exception-safe constructors: ensure that any exit path from the constructor correctly deallocates all resources that need to be.

Yes, its a pain. Yes, its nontrivial. Welcome to the field of programming; its hard. You can always switch to a managed language like C# that helps you with some of this (not that C# is a magic bullet, but there you go).

##### Share on other sites
arggh :)

ok, so I fixed it like this: (please tell me if it's really a good fix)
class::class(arguments){    if (!start(arguments)    {        destroy(); // Safely releases all pointers        throw("NOOOO!");        return;    }}

I now initialize the class like this:
try{    instance = new class(arguments);}catch (char* error){    return 0; // So far only one possible error, so no need to check what happened}

##### Share on other sites
Well, I would throw an exception class, as they make sense to throw, but other than that, yeah.

##### Share on other sites
Indeed. Throw std::exception, or one of its subclasses, or a subclass of your own creation. The classes have constructors that take message parameters, so you can do something like:

try{  throw std::runtime_exception("something bad happened");}catch(std::exception &e){  // Note - caught the base class, allows us to catch the base  // and all derived classes. Also, we caught by reference.   // This is generally good practice.  // Print the error to stderr.  std::cerr << e.what();}

##### Share on other sites
If you're not comfortable with exceptions you could try this:
Class::Class(bool& Success){  Success = false;  if(some_error) return;  if(some_other_error) return;  Success = true;}

Then:
bool Success;Class* C = new Class(Success)if(!Success){  delete C;  return some_error_code;}do_something_else;delete C;

##### Share on other sites
Not only is that pretty ugly, but it won't work for your copy constructor.

##### Share on other sites
I think I get exceptions now. I had only seen them once before, recently, so I didn't really know how to use them with my problem. Thanks for the help with that exception class, I didn't know you could do it like that as well.

Guess I'm fixed now. All I need to do now is write a function that takes another function as argument and exception-handles it :)

thanks a lot for all the helpful replies!