Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

3
  • In C++, why is the destructor called automatically only with a stack object and not with a heap object in case of an exception? Commented Dec 3, 2015 at 19:02
  • @Giorgio Because heap resources live in a memory space that isn't directly tied to the call stack. For example, imagine a multithreaded application with 2 threads, A and B. If one thread throws, rolling back A's transaction should not destroy resources allocated in B, e.g. -- the thread states are independent of each other, and persistent memory living on the heap is independent of both. However, typically in C++, heap memory is still tied to objects on the stack. Commented Dec 18, 2015 at 8:27
  • @Giorgio For example, an std::vector object might live on the stack but point to memory on the heap -- both the vector object (on the stack) and its contents (on the heap) would be deallocated during a stack unwind in that case, since destroying the vector on the stack would invoke a destructor which frees the associated memory on the heap (and likewise destroy those heap elements). Typically for exception-safety, most C++ objects live on the stack, even if they're only handles pointing to memory on the heap, automating the process of freeing both heap and stack memory on stack unwind. Commented Dec 18, 2015 at 8:29