← Back to Question List
C++ Code Walkthrough #127
Destructors Run on the Way Out
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45class Guard {6 std::string m_name;7public:8 explicit Guard(const std::string& name) : m_name(name) {9 std::cout << "open " << m_name << "\n";10 }11 ~Guard() {12 std::cout << "close " << m_name << "\n";13 }14};1516void inner() {17 Guard g("inner");18 std::cout << "inner working\n";19 throw std::runtime_error("inner failed");20 std::cout << "inner done\n";21}2223void outer() {24 Guard g("outer");25 inner();26 std::cout << "outer done\n";27}2829int main() {30 try {31 outer();32 } catch (const std::runtime_error& e) {33 std::cout << "caught: " << e.what() << "\n";34 }35 return 0;36}