V
vikram_p_nayak
I was just going through this book by Scott Meyers and did not fully
follow item 10.
Basically he says the constructor should catch all exceptions, do any
cleanups necessary and then throw. This is because otherwise the member
objects already created can not be destroyed from outside since the
container object itself is not fully created.
Look at this - (myclass contains objects of class1 and class2)
Class myclass {
class1 m_class1;
class2 m_class2;
public:
myclass(int c1, int c2):m_class1(c1), m_class2(c2) {}
}
Assume both class1 and class2 have constructors which take int
parameters.
so m_class1 gets initialized first and then m_class2. If the contructor
of class2 throws an exception, even after its own cleanup, how would it
help? m_class1 is already contructed. How is it destroyed?
I actually tried this on VC++ 6 compiler and it seems to work. As in ,
m_class1's destructor indeed gets called! I think class1 and class2
initializations are independently happening and we can not cleanup one
because of an exception in the other.
Please let me know if I am missing something here. How does the
compiled code know that m_class1 is contructed and it needs to be
destroyed whereas it passes the exception from m_class2 as is.
follow item 10.
Basically he says the constructor should catch all exceptions, do any
cleanups necessary and then throw. This is because otherwise the member
objects already created can not be destroyed from outside since the
container object itself is not fully created.
Look at this - (myclass contains objects of class1 and class2)
Class myclass {
class1 m_class1;
class2 m_class2;
public:
myclass(int c1, int c2):m_class1(c1), m_class2(c2) {}
}
Assume both class1 and class2 have constructors which take int
parameters.
so m_class1 gets initialized first and then m_class2. If the contructor
of class2 throws an exception, even after its own cleanup, how would it
help? m_class1 is already contructed. How is it destroyed?
I actually tried this on VC++ 6 compiler and it seems to work. As in ,
m_class1's destructor indeed gets called! I think class1 and class2
initializations are independently happening and we can not cleanup one
because of an exception in the other.
Please let me know if I am missing something here. How does the
compiled code know that m_class1 is contructed and it needs to be
destroyed whereas it passes the exception from m_class2 as is.