Recently an interviewer asked me where the exception object in C++ is allocated, heap or stack? I'm not sure but I answered stack since I thought there is no "new" or "malloc". Is it correct?
Then he kept asking me that if it's on stack, assuming class A throw a exception object, let's say "e", and class B catch "e". Since "e" is on the stack of A, then how does B can have the access to this "e"?
I'm not very clear about the second question. Could anyone can give me some example code showing that "class A throw e and class B catch it"? Also, I guessed B can catch e by copying the value or address but the interviewer only denied my answer without giving me right one, so what is the right answer, is there any mechanism can ensure class object can catch exceptions from other class objects? Thanks~
Stack and a Heap ? Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.
Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Ask for assistance with the Home Energy Assistance Program. Call 212-331-3126 or the HEAP Infoline at 800-692-0557 for help with HEAP.
Memory allocation in the Heap Space is accessed through a complex, young-generation, old-generation system. Stack is accessed through a last-in, first-out (LIFO) memory allocation system. Heap Space exists as long as the application runs and is larger than Stack, which is temporary, but faster.
From [except.throw]/15.1/4:
The memory for the exception object is allocated in an unspecified way, except as noted in 3.7.4.1.
The final reference, [basic.stc.dynamic.allocation]/4, says:
[Note: In particular, a global allocation function is not called to allocate storage for [...] an exception object (15.1). — end note]
It can't be stack as the when exception is thrown stack unwinds and you'd lose the exception object if allocated in the frame that caused the exception.
I remember reading something about it in C++ Primer, 5Ed. It said
The exception object resides in space, managed by the compiler, that is guaranteed to be accessible to whatever catch is invoked. The exception object is destroyed after the exception is completely handle.
And looking at @Kerrek's asnwer above along with it, I believe it's a separate space allocated and is specific to compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With