CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #146

Destroyed Once or Twice

mediumExceptions

The second Sensor throws from its constructor. How many times does destroyed print, and for which object?

📄 Code

1#include <iostream>
2#include <stdexcept>
3 
4class 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};
14 
15int 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}