In my project I found a piece of code in which a method was getting called in constructor’s initializer list.
Test2(Test* pTest):m_pTest(pTest), m_nDuplicateID(pTest->getTestID()) { }
I observed that there is a chance that the users of Test2 might pass NULL to the constructor. Since the pointer is used without validation there are chances of Access Violation.
This triggered me to look into exception handling in constructor’s initializers list. I found in one of the article that try can be used inside initializer list. I wrote small test program to test this concept:
//Test class stores the unique ID and returns the same with API getTestID class Test { public: Test(int nID):m_nID(nID){ } int getTestID() const { return m_nID; } private: int m_nID; }; class Test2 { public: Test2(Test* pTest) try :m_pTest(pTest), m_nDuplicateID(pTest->getTestID()) { } catch (...) { cout<<'exception cought '<< endl; } void printDupID() { cout<<'Duplicate ID' << m_nDuplicateID << endl; } private: Test* m_pTest; int m_nDuplicateID; }; int main(int argc, char* argv[]) { Test* pTest = new Test(10); Test2 aTest2(pTest); aTest2.printDupID(); delete pTest; return 0; }
This code is not getting compiled in VC6.0. Do I need to make any changes to make it compile in VC 6.0?
Also, in one of the article I found that using try in constructor’s initializer list does not strictly confirms to C++ standards. In that case, how do we handle the exceptions in constructor’s initializers list (standard way of handling )?
Thanks.
Firstly, if you dereference the NULL pointer standard C++ does not guarantee that that an exception will be thrown, so your code is useless for this case.
Secondly, if an exception were thrown, what would your exception handler do?
Thirdly, constructor/function exception blocks are widely considered to be awaste of time – take a look at this http://www.gotw.ca/gotw/066.htm and other articles on Herb Sutter’s GotW site.