gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:44:19 25 4
gpt4 key购买 nike

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

 //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;
}

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

谢谢!

最佳答案

您似乎使用了错误的共享/弱指针对。标准(在 C++11 和 boost 中)共享/弱指针允许你毫无异常(exception)地做到这一点:

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
}

您可能还想查看我在 this stackoverflow answer 中提供的代码示例

关于C++:是否有理由在非异常情况下使用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com