Where does the exception object have its space, heap or stack and how to access it in different classes?

Recently an interviewer asked me where is the C ++ exception object allocated, the heap or the stack? I'm not sure, but I answered the stack since I thought there was no "new" or "malloc", Is that correct?

Then he kept asking me what if it is on the stack, if class A picked an exception object, say "e" and class B would catch "e". Since "e" is on A's stack, how can B have access to this "e"?

I don't really understand the second question. Can anyone give me some example code showing that "class A throw e and class B will catch it"? Also, I guessed that B could catch e by copying the value or address, but the interviewer only discarded my answer without giving me the correct answer, so what's the correct answer, is there any mechanism that can guarantee that the class object can catch exceptions from other class objects? Thanks ~

+3


source to share


4 answers


From [except.throw] /15.1/4:

Memory for the exception object is assigned in an unspecified manner, except as specified in 3.7.4.1.



The last link, [basic.stc.dynamic.allocation] / 4, says:

[Note. In particular, the global allocator is not called to allocate storage for the [...] exception object (15.1). - end note]

+7


source


It cannot be a stack, because an exception causes the stack to be flushed and you will lose the exception object if it is allocated in the frame that caused the exception.

I remember reading something in the C ++ Primer, 5Ed. He said



The exception object is in compiler-managed space, which is guaranteed to be available for any catch call. The exception object is destroyed when the exception is completely removed.

And looking at @Kerrek asnwer above along with it, I believe this is allocated space and is compiler specific.

+1


source


"but I answered the stack as I thought there was no" new "or" malloc ". Is that correct?"

Basically yes, although the exception handling is a little special because it unwinds the stack for operations throw

.

 struct SomeException {
 };

 void throwing_func() {
      throw SomeException();
 }

 int main() {
     try {
         throwing_func();
     }
     catch(const SomeException& ex) {
         std::cout << "Caught 'SomeException' exception" << std::endl;
     }
 }

      

Local area

void throwing_func() {
      throw SomeException();
}

      

is somehow equivalent when looking at local scope

and matching that type local scope

with the best convention catch(...)

.

0


source


throw new std :: exception vs throw std :: exception

The above link has a pretty good answer.

I think the answer will be "usually" on the heap as you are throwing an object that will be on the heap, but if it is a static object (not sure if such a thing exists) then it will be on the stack.

0


source







All Articles