How is the C++ exception handling runtime implemented?

后端 未结 4 848
梦毁少年i
梦毁少年i 2020-11-28 21:54

I am intrigued by how the C++ exception handling mechanism works. Specifically, where is the exception object stored and how does it propagate through several scopes until i

4条回答
  •  無奈伤痛
    2020-11-28 22:20

    This is defined in 15.1 Throwing an exception of the standard.

    The throw creates a temporary object.
    How the memory for this temporary object is allocated is unspecified.

    After creation of the temporary object control is passed to the closest handler in the call stack. unwinding the stack between throw and catch point. As the stack is unwind any stack variables are destroyed in reverse order of creation.

    Unless the exception is re-thrown the temporary is destroyed at the end of the handler where it was caught.

    Note: If you catch by reference the reference will refer to the temporary, If you catch by value the temporary object is copied into the value (and thus requires a copy constructor).

    Advice from S.Meyers (Catch by const reference).

    try
    {
        // do stuff
    }
    catch(MyException const& x)
    {
    }
    catch(std::exception const& x)
    {
    }
    

提交回复
热议问题