You've answered 1 of 188 questions correctly. (Clear)
Question #323 Difficulty:
According to the C++23 standard, what is the output of this program?
#include <iostream>
#include <stdexcept>
struct A {
A(char c) : c_(c) {}
~A() { std::cout << c_; }
char c_;
};
struct Y { ~Y() noexcept(false) { throw std::runtime_error(""); } };
A f() {
try {
A a('a');
Y y;
A b('b');
return {'c'};
} catch (...) {
}
return {'d'};
}
int main()
{
f();
}
Correct!
This is taken from an example in §[except.ctor]¶2 in the standard about stack unwinding:
Each object with automatic storage duration is destroyed if it has been constructed, but not yet destroyed, since the try block was entered. If an exception is thrown during the destruction of temporaries or local variables for a
returnstatement (§[stmt.return]), the destructor for the returned object (if any) is also invoked. The objects are destroyed in the reverse order of the completion of their construction.[Example 1:
struct A { }; struct Y { ~Y() noexcept(false) { throw 0; } }; A f() { try { A a; Y y; A b; return {}; // #1 } catch (...) { } return {}; // #2 }At #1, the returned object of type
Ais constructed. Then, the local variablebis destroyed (§[stmt.jump]). Next, the local variableyis destroyed, causing stack unwinding, resulting in the destruction of the returned object, followed by the destruction of the local variablea. Finally, the returned object is constructed again at #2. — end example]
It is worth noting that at the time of writing, neither GCC, Clang nor MSVC conform to the behaviour described in the standard, and instead print bacd, bad and bad, respectively.
You can explore this question further on C++ Insights or Compiler Explorer!
Mode : Training
You are currently in training mode, answering random questions. Why not Start a new quiz? Then you can boast about your score, and invite your friends.
Contribute
C++ Brain Teasers
Get the book, support the site!