Sign in to follow this  
shoez

Throwing Exception in constructor?

Recommended Posts

shoez    104
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
smart_idiot    1298
[list=1][*]If an exception is thrown inside the constructor for an object, then that object's destructor is [b]NOT[/b] called. The destructors of any member objects it contains, and the destructors of any classes it inherits from however will be.[*]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.[/list]

Share this post


Link to post
Share on other sites
Bregma    9214
[quote name='shoez' timestamp='1302913470' post='4798986']
im guessing i would need to create my own RAII object for this then?
[/quote]

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

Share this post


Link to post
Share on other sites
SiCrane    11839
Or the ATL [url=http://msdn.microsoft.com/en-us/library/5fc6ft2t(v=VS.100).aspx]CHandle[/url] class.

Share this post


Link to post
Share on other sites
jyk    2094
[quote name='smart_idiot' timestamp='1302922833' post='4799014']
I believe shared_ptr is part of C++0x, which may not be something one would want to mess with yet.
[/quote]
There's always the Boost version though.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this