← Back to Question List
C++ Quiz #145
Guards Closing During Unwinding
Each function owns a Guard that prints when it is built and when it is destroyed. inner() throws. What is printed?
📄 Code
1#include <iostream>2#include <stdexcept>3#include <string>45struct Guard {6 std::string name;7 Guard(const std::string& n) : name(n) { std::cout << "open " << name << "\n"; }8 ~Guard() { std::cout << "close " << name << "\n"; }9};1011void inner() {12 Guard g("inner");13 throw std::runtime_error("fail");14}1516void outer() {17 Guard g("outer");18 inner();19 std::cout << "after inner\n";20}2122int main() {23 try {24 outer();25 } catch (const std::exception& e) {26 std::cout << "caught " << e.what() << "\n";27 }28 return 0;29}