My understanding of exception stack unwinding is that modifications to an array will be "as-if" they never occurred:
#include <array>
#include <stdexcept>
#include <algorithm>
#include <iostream>
int main() {
std::array<int,10> foo = {};// zero-initialize
try {
std::fill_n(begin(foo), 10, 1);// assign all ones
throw std::runtime_error("intentional");
}
catch (const std::exception&) {
}
std::cout << foo[0];// foo remains unchanged, i.e. all zeros
}
Am I correct in this; does stack unwinding ensure variable "foo" is all zeros after the catch block?
And if I am correct, surely this must have performance considerations. To undo modifications to "foo" would require either a backup copy in memory, or some real execution tricks to recover it's original state.
does stack unwinding ensure variable "foo" is all zeros after the catch block?
No, of course not.
For one thing, std::array
is not itself an array, it is a struct object that holds an array as a data member.
And second, stack unwinding does not undo code that has already been executed. All it does is destroy any local objects that were created inside the try
block that are still alive at the time the exception is thrown.
You already modified the content of the std::array
before the exception is thrown. That will not be undone by stack unwinding.
To undo modifications to "foo" would require either a backup copy in memory, or some real execution tricks to recover it's original state.
Yes, exactly, and the compiler will not do that kind of stuff for you. If you want this, you have to do it yourself.