Let me give you the following example: Imagine you have a window class which can have child windows. Each child window holds a weak pointer to its parent window, each window has a list of shared ptrs to its children. Now i have the situation that if the child window is destructed, I can't know if it is destructed because the parent window was closed, or because the child window itself was closed. Therefore the solution I came up with was to dereference the parent windows weak pointer in the child windows destructor in a try{}catch{} block to see if the parent window still exists (pseudocode):
//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;
}
In this situation I could not think of another way to solve this simply because there is no way to know the context in which the destructor was called. Is this a stupid thing to do because I use an exception in a sort of expected situation? I know this is not a thing you want to do in performance critical code so this is not the point of the question.
Thank you!