是否确定在我的构造函数下面的代码将XML文档加载到一个成员变量 - 抛来打电话的人是否有任何问题:基于斯科特在CTOR和智能抛出异常指针
MSXML2::IXMLDOMDocumentPtr m_docPtr; //member
Configuration()
{
try
{
HRESULT hr = m_docPtr.CreateInstance(__uuidof(MSXML2::DOMDocument40));
if (SUCCEEDED(hr))
{
m_docPtr->loadXML(CreateXML());
}
else
{
throw MyException("Could not create instance of Dom");
}
}
catch(...)
{
LogError("Exception when loading xml");
throw;
}
}
更有效的C++,如果他alocates他清理迈尔斯RAII实现的任何资源,即指针:
BookEntry::BookEntry(const string& name,
const string& address,
const string& imageFileName,
const string& audioClipFileName)
: theName(name), theAddress(address),
theImage(0), theAudioClip(0)
{
try { // this try block is new
if (imageFileName != "") {
theImage = new Image(imageFileName);
}
if (audioClipFileName != "") {
theAudioClip = new AudioClip(audioClipFileName);
}
}
catch (...) { // catch any exception
delete theImage; // perform necessary
delete theAudioClip; // cleanup actions
throw; // propagate the exception
}
}
我相信我在短短允许例外,从CTOR因为我使用的是智能指针(IXMLDOMDocumentPtr)被抛出正常的。
让我知道你在想什么......
为什么'try {...} ... catch(...){}'?可以修复代码,使其看起来像构造函数定义,否则提供建设性的批评有点困难。 – 2010-06-09 10:46:53
我不明白你的问题。通常可以从构造函数中抛出异常。你关心什么?你有什么替代方案? – 2010-06-09 10:56:52
当你抛出异常时,你担心'm_docPtr'变量是否被破坏? – Naveen 2010-06-09 11:01:42