C++:在非特殊情况下是否有理由使用异常

mok*_*oka 2 c++ exception

让我举几个例子:想象一下,你有一个可以有子窗口的窗口类.每个子窗口都有一个指向其父窗口的弱指针,每个窗口都有一个与其子窗口共享的ptrs列表.现在我的情况是,如果子窗口被破坏,我不知道它是否被破坏,因为父窗口已关闭,或者因为子窗口本身已关闭.因此,我提出的解决方案是在try {} catch {}块中取消引用子窗口析构函数中的父窗口弱指针,以查看父窗口是否仍然存在(伪代码):

 //we try to retain the parent window here
 try
 {
     //creates a shared pointer from the weak pointer, throws BadReferenceCounterException on fail
     WindowPtr parent = m_parentWindow.retain();

     //check if there is a parent at all, otherwise 0
     if(parent)
     {
         parent->removeChildWindow(this);
     }
  }
  catch(const BadReferenceCounterException & _ec)
  {
     std::cout<<"Catched expected exception, if Parent was closed before me!"<<std::endl;
  }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想不出另一种方法来解决这个问题,因为无法知道调用析构函数的上下文.这是一个愚蠢的事情,因为我在某种预期的情况下使用异常?我知道这不是你想要在性能关键代码中做的事情,所以这不是问题的关键.

谢谢!

bro*_*ekk 5

您似乎使用了错误的共享/弱指针对.标准(在C++ 11和boost中)共享/弱指针允许您无异常地执行此操作:

typedef std::shared_ptr<Window> WindowPtr;
typedef std::weak_ptr<Window> WeakWindowPtr;

WeakWindowPtr m_parentWindow;
//...

WindowPtr parent = m_parentWindow.lock();
if (parent)
{
  // here you know parent wasn't destroyed and you can access it via parent
}
Run Code Online (Sandbox Code Playgroud)

您可能还想查看我在此stackoverflow答案中给出的代码示例