One of the main benefits of using smart pointers over raw pointers is that they are exception safe, meaning that if a program terminates before reaching the end of scope, the underlying object will still be destroyed, preventing a memory leak.
In this program, the constructor and destructor are both printed, as expected:
struct Entity {
Entity() { std::cout << "Created Entity" << std::endl; }
~Entity() { std::cout << "Destroyed Entity" << std::endl; }
};
int main() {
std::shared_ptr<Entity> p = std::make_shared<Entity>();
}
However, I would expect the same behavior here, but "Destroyed Entity" is not displayed after the exception is reached.
int main() {
std::shared_ptr<Entity> p = std::make_shared<Entity>();
throw;
}
Is it still destroying the underlying object and just not displaying it? Or am I misunderstanding exception safety on a conceptual level? Thanks