LearnFrenzy
Sign in Take a free test

Exception Handling · Predict the Output · Question 4

Destructor order during stack unwinding Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>

struct T {
    char c;
    explicit T(char x) : c(x) { std::cout << '+' << c; }
    ~T() { std::cout << '-' << c; }
};

void inner() { T x('x'); T y('y'); throw std::runtime_error("e"); }
void outer() { T a('a'); inner(); T b('b'); }

int main() {
    try { outer(); }
    catch (const std::exception& e) { std::cout << " caught " << e.what(); }
    std::cout << '\n';
    return 0;
}
  • A +a+x+y-y-x-a caught e Correct
  • B +a+x+y-a-x-y caught e
  • C +a+x+y caught e-y-x-a
  • D +a+x+y+b-b-y-x-a caught e
Correct Answer: Option A

Locals are destroyed in reverse order, function by function, before the handler runs. b is never constructed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links