Exception object lifetime

后端 未结 1 1861
无人共我
无人共我 2021-01-17 21:55

I want to know how the exception object is created ? and why the handler function parameter can be a non-const reference?

For example:

class          


        
相关标签:
1条回答
  • 2021-01-17 22:25

    want to know how the exception object is created ?

    When you do this:

    throw E("Out of memory");
    

    You create an object (of type E) locally. The processes of throwing copies this object to some private memory location not defined by the standard. Thus the object being thrown must be copyable.

    Note: the compiler is allowed to optimize out the copy and create it directly in the private location. So the fact that it is not copied is because the compiler optimized away the copy (so it is not local anymore). Try making the copy constructor private and now it will fail to compile.

    and why the handler function parameter can be a non-const reference ?

    When you catch the object:

    catch(E& e)
    

    You are getting a reference to the object at the private location it was copied to. Its not a const (or temporary) value so you can have a normal reference to it.

    0 讨论(0)
提交回复
热议问题