Using std::shared_ptr with custom deleters in C++17 causing double free errors
I'm not sure how to approach Hey everyone, I'm running into an issue that's driving me crazy. Quick question that's been bugging me - I'm working with an scenario with `std::shared_ptr` and custom deleters in C++17. I created a class that manages a resource, and I want to ensure proper cleanup by using a custom deleter. However, I'm consistently working with a double free behavior when the `std::shared_ptr` goes out of scope. Here's a simplified version of my code: ```cpp #include <iostream> #include <memory> class Resource { public: Resource() { std::cout << "Resource acquired\n"; } ~Resource() { std::cout << "Resource released\n"; } }; void customDeleter(Resource* res) { std::cout << "Custom deleter called\n"; delete res; } int main() { std::shared_ptr<Resource> res1(new Resource(), customDeleter); std::shared_ptr<Resource> res2 = res1; // Copying the shared_ptr // Manually resetting the shared_ptr, I think this is where things go wrong res1.reset(); res2.reset(); // Double free happens here } ``` In this code, I create a `shared_ptr` with a custom deleter that deletes the `Resource` object when it is no longer needed. However, when I reset `res1` and then `res2`, I receive the following behavior messages: ``` *** behavior in `./a.out`: double free or corruption (fasttop): 0x0000000001b53140 *** Aborted ``` I've tried ensuring that I'm not manually deleting the resource elsewhere and confirmed that the deleter is not being called twice explicitly. I suspect it might be related to how `shared_ptr` handles copies and the custom deleter, but I'm not sure how to resolve this. Can anyone provide insights on what might be causing this double free, and how I can safely manage the resource with a custom deleter? Thanks! This issue appeared after updating to Cpp 3.9. How would you solve this? This is part of a larger application I'm building. Any ideas how to fix this?