Re: is such exception handling approach good?
George schrieb:
Thanks Norbert,
Looks like you have better ideas to handle the case when there are
exceptions in destructor. Cool!
No, you misunderstood me, I guess I was not clerar enough.
The rule stands: Don't throw exceptions in destructors.
If there are cases where fstream::close might throw an exception then make sure
you do not call close when one of the conditions is true. Or do not call close
at all in the destructor. I'd hope that fstream's destructor does the required
cleanup work without throwing. However, I do not know if the standard library
class' destructors are generally guaranteed not to throw.
But I do not 100% understand. :-)
For this case,
* Avoid using new/delete for arrays. Use std::vector<> instead.
Why using vector is better? Because vector does not leak any resources even
if there are exceptions? Could you provide more descriptions please?
The point is that std::vector takes care of its memory. You can of course use
new/delete in your class and be safe as well. But this requirews great care when
implementing the class. You must make sure that for every member pointer you
have you set it to 0 or allocate memory in all constructors and call delete in
the destructor. You always have the risc that you forget one when adding or
removing members during the development phase.
If you always use smart pointers or std containers, you know you are always
clean without any additinal thinking.
(I think you mean if we use new, and we may have exceptions when using
delete, and such exception will cause memory not fully freed and will cause
potential memory leak?) Right?
no, using std::vector instead of new does not solve this issue. It just makes it
implssible to forget to call delete in the destructor.
Norbert