Problem
What will the following code print to stdout
?
1#include <iostream>
2
3using namespace std;
4
5struct A {
6 A() { cout << __PRETTY_FUNCTION__ << endl; }
7 virtual ~A() { cout << __PRETTY_FUNCTION__ << endl; }
8};
9
10struct C {
11 C() { cout << __PRETTY_FUNCTION__ << endl; }
12 ~C() { cout << __PRETTY_FUNCTION__ << endl; }
13};
14
15struct D {
16 D() { cout << __PRETTY_FUNCTION__ << endl; }
17 ~D() { cout << __PRETTY_FUNCTION__ << endl; }
18};
19
20struct E {
21 E() { cout << __PRETTY_FUNCTION__ << endl; }
22 E(const E&) { cout << __PRETTY_FUNCTION__ << endl; }
23 ~E() { cout << __PRETTY_FUNCTION__ << endl; }
24};
25
26struct B: A {
27 D d;
28
29 B() {
30 try {
31 C c;
32 throw E();
33 } catch (E e) {
34 cout << "catch" << endl;
35 }
36 throw E();
37 }
38
39 ~B() { cout << __PRETTY_FUNCTION__ << endl; }
40};
41
42int main() {
43 try {
44 B b;
45 } catch (const E&) {
46 }
47
48 return 0;
49}
Solution
Explanation
try
block inmain()
.- Default initialization of local variable
b
inmain()
. - Default constructor of a base class
A::A()
. - Default initialization of data member
B::d
. - Default constructor
D::D()
. - Default constructor
B::B()
. - Default initialization of local variable
c
inB::B()
. - Default constructor
C::C()
. - Throw exception object
E
(temporary object with unspecified duration). - Default constructor
E::E()
. - Stack unwinding.
- Destructor
C::~C()
(object with automatic storage duration) at the end oftry
block. catch
exception objectE
by value.- Copy initialization of exception object: copy constructor
E::E(const E&)
. - Print
catch
. - Destructor
E::~E()
(exception object from step 14) at the end oftry-catch
clause. - Destructor
E::~E()
(exception object from step 10) at the end oftry-catch
clause. - Throw exception object
E
(temporary object with unspecified duration). - Default constructor
E::E()
. catch
exception objectE
by constant reference inmain()
.- End of
try-catch
clause inmain()
. - Destructor
D::~D()
of data memberB::d
initialized in step 4. - Virtual destructor
A::~A()
of base classA
initialized in step 3. - Destructor
E::~E()
(exception object from step 19) at the end ofmain()
.