Index: src/script/api/script_testmode.cpp =================================================================== --- src/script/api/script_testmode.cpp (revision 27378) +++ src/script/api/script_testmode.cpp (working copy) @@ -30,7 +30,7 @@ this->SetDoCommandMode(&ScriptTestMode::ModeProc, this); } -ScriptTestMode::~ScriptTestMode() +void ScriptTestMode::FinalRelease() { if (this->GetDoCommandModeInstance() != this) { /* Ignore this error if the script already died. */ @@ -38,5 +38,9 @@ throw Script_FatalError("Testmode object was removed while it was not the latest *Mode object created."); } } +} + +ScriptTestMode::~ScriptTestMode() +{ this->SetDoCommandMode(this->last_mode, this->last_instance); } Index: src/script/api/script_execmode.cpp =================================================================== --- src/script/api/script_execmode.cpp (revision 27378) +++ src/script/api/script_execmode.cpp (working copy) @@ -30,7 +30,7 @@ this->SetDoCommandMode(&ScriptExecMode::ModeProc, this); } -ScriptExecMode::~ScriptExecMode() +void ScriptExecMode::FinalRelease() { if (this->GetDoCommandModeInstance() != this) { /* Ignore this error if the script already died. */ @@ -38,5 +38,9 @@ throw Script_FatalError("ScriptExecMode object was removed while it was not the latest *Mode object created."); } } +} + +ScriptExecMode::~ScriptExecMode() +{ this->SetDoCommandMode(this->last_mode, this->last_instance); } Index: src/script/api/script_testmode.hpp =================================================================== --- src/script/api/script_testmode.hpp (revision 27378) +++ src/script/api/script_testmode.hpp (working copy) @@ -48,6 +48,8 @@ * in when the instance was created. */ ~ScriptTestMode(); + + virtual void FinalRelease(); }; #endif /* SCRIPT_TESTMODE_HPP */ Index: src/script/api/script_execmode.hpp =================================================================== --- src/script/api/script_execmode.hpp (revision 27378) +++ src/script/api/script_execmode.hpp (working copy) @@ -46,6 +46,8 @@ * in when the instance was created. */ ~ScriptExecMode(); + + virtual void FinalRelease(); }; #endif /* SCRIPT_EXECMODE_HPP */ Index: src/misc/countedobj.cpp =================================================================== --- src/misc/countedobj.cpp (revision 27378) +++ src/misc/countedobj.cpp (working copy) @@ -25,7 +25,12 @@ int32 res = --m_ref_cnt; assert(res >= 0); if (res == 0) { - FinalRelease(); + try { + FinalRelease(); + } catch (...) { + delete this; + throw; + } delete this; } return res;