• Advertisement
Sign in to follow this  

Throwing Exception in constructor?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have the following questions about throwing exceptions while in an objects constructor.
1.) If you throw an exception in a constructor...does the destructor for that object get called?
2.) If your throw an exception in a constructor, does an opened handle(on windows) or file pointer(in C/C++) remain open and memory leaked until your manually release the resource?

Share this post


Link to post
Share on other sites
Advertisement
  1. If an exception is thrown inside the constructor for an object, then that object's destructor is NOT called. The destructors of any member objects it contains, and the destructors of any classes it inherits from however will be.
  2. Exception handling won't do anything about any open files or allocated objects unless they're managed in some objects destructor (like std::filebuf or std::auto_ptr) or explicitly dealt with in a try/catch block. As such, the answer is probably yes, you'll create a leak if an exception is thrown.

Share this post


Link to post
Share on other sites
awesome information, im just curious can you use auto_ptr with handles in windows?

Share this post


Link to post
Share on other sites
No, std::auto_ptr cannot be used with a Windows HANDLE. Since we're on the subject, it also can't be used for arrays.

Share this post


Link to post
Share on other sites
im guessing i would need to create my own RAII object for this then?

Share this post


Link to post
Share on other sites

im guessing i would need to create my own RAII object for this then?


Or use [font="Courier New"]std::shared_ptr [/font]with a destructor argument.

Share this post


Link to post
Share on other sites

I believe shared_ptr is part of C++0x, which may not be something one would want to mess with yet.

There's always the Boost version though.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement