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

别说谁变了你拦得住时间么 提交于 2019-12-05 08:41:08

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.

"but I answered stack since I thought there is no "new" or "malloc". Is it correct?"

Basically yes, though exception handling is a bit special because it unwinds the stack for throw operations.

 struct SomeException {
 };

 void throwing_func() {
      throw SomeException();
 }

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

The local scope of

void throwing_func() {
      throw SomeException();
}

is somehow equivalent as looking to a local scope and matching that kind of local scope with the best matching catch(...) statement.

Bhaskar Bhattacharya

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

The above link has a pretty good answer.

I think the answer would be "usually" heap since you are throwing an object which would be located on the heap but if it is a static object (not sure if such a thing exists) then it would be on the stack.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!