I've seen several similar snippets of code that looked like this:
struct MyExcept : std::exception {
explicit MyExcept(const char* m) noexcept : message{m} {}
const char* what() const noexcept override {
return message;
}
const char* message;
};
void foo() {
std::string error;
error += "Some";
error += " Error";
throw MyExcept{error.c_str()};
}
int main() {
try {
foo();
} catch (const MyExcept& e) {
// Is this okay?
std::cout << e.message << std::endl;
}
}
In the line following the comment Is this okay?
, we read the c-style string that was allocated in the foo
function using std::string
. Since the string is destructed with stack unwinding, is this undefined behavior?
If it's indeed undefined behavior, what if we replace the main
function with this one?
int main() {
foo();
}
Since there is no catch, the compiler is not forced to unwind the stack, and yet output the result of what()
in the console and abort the program. So is it still undefined behavior?