Please consider the following C++20 program:
struct S1 {
~S1() { std::cout << "~S1" << std::endl; }
};
struct S2 {
S1 s1;
S2() {
throw std::runtime_error("error");
}
~S2() {
std::cout << "~S2" << std::endl;
}
};
int main() {
try {
S2* s2 = new S2;
} catch (...) {
}
}
The output of this program is:
~S1
I think because the constructor of S2 didn't complete, the body of its desctructor isn't run, but the destructors of subobjects that did complete construction are run.
What I'm not sure about is the new expression. Clearly it must allocate memory for the object before it starts executing the constructor. Given that the constructor exited with an exception, is this allocated memory automatically freed as well?
The question is: does the above program leak memory? (As in, absolutely guaranteed by the standard? No undefined/unspecified behaviour?)