2010-06-09 60 views
0

是否确定在我的构造函数下面的代码将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)被抛出正常的。

让我知道你在想什么......

+4

为什么'try {...} ... catch(...){}'?可以修复代码,使其看起来像构造函数定义,否则提供建设性的批评有点困难。 – 2010-06-09 10:46:53

+0

我不明白你的问题。通常可以从构造函数中抛出异常。你关心什么?你有什么替代方案? – 2010-06-09 10:56:52

+0

当你抛出异常时,你担心'm_docPtr'变量是否被破坏? – Naveen 2010-06-09 11:01:42

回答

1

C++保证在发生异常的情况下,所有完全构造的对象都将被销毁。

由于m_docPtrclass Configuration成员也将有class Configuration构造函数体开始之前被完全构造,所以如果你从class Configuration身体抛出一个异常,因为你在第一个片段预期m_docPtr将被销毁。

+0

我调用createInstance这个事实吗? – 2010-06-09 11:42:55

+1

不,“m_docPtr”的析构函数将被无条件调用。 – sharptooth 2010-06-09 11:49:40

0

你打算做什么在catch块?如果没有,你可能不需要尝试捕获。在Windows上,我相信catch(...)会捕获硬件中断(请专家指正),请记住这一点。