CodexBloom - Programming Q&A Platform

std::unique_ptr not releasing resources after handling in custom deleter

๐Ÿ‘€ Views: 20 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-05
c++ memory-management exceptions C++

Does anyone know how to I've been banging my head against this for hours. I'm working with an scenario with `std::unique_ptr` that uses a custom deleter. The question arises when an exception is thrown during construction of the object being managed by the `unique_ptr`. I expected the custom deleter to be called and resource to be released, but it seems that the pointer remains allocated, resulting in a memory leak. Hereโ€™s a simplified version of my code: ```cpp #include <iostream> #include <memory> #include <stdexcept> struct CustomDeleter { void operator()(int* ptr) const { std::cout << "Deleting resource: " << *ptr << '\n'; delete ptr; } }; int main() { try { std::unique_ptr<int, CustomDeleter> ptr(new int(42)); // Simulate an behavior during some operation throw std::runtime_error("Something went wrong"); } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << '\n'; } // ptr goes out of scope here, but was not deleted } ``` When I run this code, I see the exception message, but the `Deleting resource` line never prints, indicating that the `CustomDeleter` is not invoked. I made sure that my `unique_ptr` is in the correct scope, and I expected it to be destroyed when the exception is thrown. Did I miss something about how `std::unique_ptr` handles exceptions, or is there a best practice to ensure the resources are cleaned up properly in such situations? I've also tried checking if the custom deleter throws its own exceptions, but that doesnโ€™t seem to be the case. Any insights would be appreciated. I've been using C++ for about a year now.