← Back to Question List
C++ Quiz #146
Destroyed Once or Twice
The second Sensor throws from its constructor. How many times does destroyed print, and for which object?
📄 Code
1#include <iostream>2#include <stdexcept>34class Sensor {5public:6 Sensor(int id) {7 std::cout << "building " << id << "\n";8 if (id < 0) {9 throw std::invalid_argument("bad id");10 }11 }12 ~Sensor() { std::cout << "destroyed\n"; }13};1415int main() {16 try {17 Sensor a(1);18 Sensor b(-1);19 std::cout << "both ready\n";20 } catch (const std::exception& e) {21 std::cout << "caught: " << e.what() << "\n";22 }23 return 0;24}