...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception> #include <iostream> struct S : std::exception { const char *what() const noexcept override { return "My custom exception"; } }; void f() { try { throw S(); } catch (std::exception e) { std::cout << e.what() << std::endl; } } |
Noncompliant Code Example
In this noncompliant code example, the variable declared by the exception-declaration is an lvalue pointer. Unfortunately the lifetime of the temporary object does not extend to beyond the exception declaration, leaving a dangling pointer. This violates EXP54-CPP. Do not access an object outside of its lifetime.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception>
#include <iostream>
struct S : std::exception {
const char *what() const noexcept override {
return "My custom exception";
}
};
void f() {
try {
S s;
throw &s;
} catch (std::exception* e) {
std::cout << e->what() << std::endl;
}
} |
Compliant Solution
In this compliant solution, the variable declared by the exception-declaration is an lvalue reference. The call to what()
results in executing S::what()
instead of std::exception::what()
.
...