Are you getting an abnormal program termination?
I believe your CCriticalSection
object will be released CSingleLock
's destructor. The destructor will get called always since this is an object on the stack. When the usercode throws, all stacks between the throw
and the catch in your function will be unwound.
However, chances are that some other object in your user code or even the CSingleLock
destructor has thrown another exception in the meantime. In this case the m_CriticalSection
object will not get released properly and std::terminate
is called and your program dies.
Here's some sample to demonstrate. Note: I am using a std::terminate
handler function to notify me of the state. You can also use the std::uncaught_exception
to see if there are any uncaught exceptions. There is a nice discussion and sample code on this here.
struct S {
S() { std::cout << __FUNCTION__ << std::endl; }
~S() { throw __FUNCTION__; std::cout << __FUNCTION__ << std::endl; }
};
void func() {
try {
S s;
{
throw 42;
}
} catch(int e) {
std::cout << "Exception: " << e << std::endl;
}
}
void rip() {
std::cout << " help me, O mighty Lord!\n"; // pray
}
int main() {
std::set_terminate(rip);
try {
func();
}
catch(char *se) {
std::cout << "Exception: " << se << std::endl;
}
}
Read this FAQ for clarity.
Can I solve this problem by putting CSingleLock outside of try block ?
Hard to say without having a look at the stack and error(s)/crashes. Why don't you give it a try. It may also introduce a subtle bug by hiding the real problem.