To have a less contrived example, I recently discovered this potential leak in my code when allocating nodes with a given allocator object.
std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type^ v) { char* buffer = al.allocate(sizeof(node));
It is less obvious how to fix this due to the buffer, but with the help I got it:
struct only_deallocate { allocator* a; size_type s; only_deallocate(allocator& alloc, size_type size):a(&alloc), s(size) {} template<class T> void operator()(T* ptr) {a->deallocate(ptr, s);} operator alloc_aware() const {return alloc_aware(*a, s);} }; std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type& v) { std::unique_ptr<node, only_deallocate> buf(alloc.allocate(sizeof(node)),{alloc, sizeof(node)});
Code compilation here
source share