CodexBloom - Programming Q&A Platform

Unexpected Performance Degradation When Using std::unique_ptr with Custom Deleter in C++20

πŸ‘€ Views: 96 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
c++20 smart-pointers performance C++

I've been banging my head against this for hours... I'm experiencing unexpected performance degradation in my C++20 application when using `std::unique_ptr` with a custom deleter. My setup involves a class that manages a vector of `std::unique_ptr` objects, each initialized with a custom deleter that logs the deletion operation. However, I noticed that the performance drops significantly when the vector size increases, especially when I try to clear or reset the vector. Here’s a simplified version of the relevant code: ```cpp #include <iostream> #include <memory> #include <vector> class CustomDeleter { public: void operator()(int* ptr) const { std::cout << "Deleting integer: " << *ptr << '\n'; delete ptr; } }; class Manager { std::vector<std::unique_ptr<int, CustomDeleter>> data; public: void add(int value) { data.push_back(std::unique_ptr<int, CustomDeleter>(new int(value), CustomDeleter())); } void clear() { data.clear(); // Performance drops here } }; int main() { Manager manager; for (int i = 0; i < 100000; ++i) { manager.add(i); } manager.clear(); // This takes too long compared to expected return 0; } ``` When I call `manager.clear()`, it seems to take an excessive amount of time relative to the number of elements stored. I expected that clearing a vector of smart pointers would be efficient, but it appears to be slowing down significantly as the size increases. I've checked that I'm not doing any additional operations inside the clear method that could cause this delay. I also tried using a lambda instead of a custom class for the deleter, but the issue persisted. Is there something inherently inefficient about using `std::unique_ptr` with a custom deleter in this specific scenario, or could it be related to how memory allocation for the vector is handled? Any insights or suggestions for improving performance would be greatly appreciated! This is part of a larger mobile app I'm building. Has anyone else encountered this? My team is using C++ for this mobile app. Any help would be greatly appreciated!