【发布时间】:2010-10-16 08:54:00
【问题描述】:
在我的项目中,我发现了一段代码,其中在构造函数的初始化列表中调用了一个方法。
Test2(Test* pTest):m_pTest(pTest), m_nDuplicateID(pTest->getTestID())
{
}
我观察到 Test2 的用户可能会将 NULL 传递给构造函数。由于指针在未经验证的情况下使用,因此存在访问冲突的可能性。
这促使我在构造函数的初始化列表中查看异常处理。我在一篇文章中发现 try 可以在初始化列表中使用。我写了一个小测试程序来测试这个概念:
//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;
}
此代码未在 VC6.0 中编译。我是否需要进行任何更改才能在 VC 6.0 中编译?
另外,在一篇文章中,我发现在构造函数的初始化列表中使用 try 并不严格符合 C++ 标准。在这种情况下,我们如何处理构造函数的初始化列表中的异常(标准处理方式)?
谢谢。
【问题讨论】:
-
VC6 因不符合标准 C++ 而臭名昭著。