Question 1
It depends. An std::vector won't actually release any underlying buffer memory even if it's no longer required, so you can't rely on removing the elements in order to free the memory used to store them.
e.g
std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vec.clear();
//vec still owns a buffer large enough to hold its initial elements
Well, you could now reasonably say that "ok, no problem! I'll just use std::vector::resize". The problem with this method is that it only resizes the buffer when the requested size is bigger than the buffer's current size.
In order to free the memory allocated by the std::vector itself, the swap idiom is used, where you construct a new empty vector and you swap it with the original.
Continuing from the previous example
std::vector<int> empty{};
vec.swap(empty);
std::list also has a swap method, so implementing a template function that works for both using the swap idiom is possible, even though you don't need it for a list because the node used to store an element is released when its removed.
A more C++/STL way to do it would be
template<template<typename ElementType, typename Alloc>
class ContType,
typename ElementType,
typename Alloc>
void clear_mem(ContType<ElementType*, Alloc>& container)
{
std::for_each(container.begin(), container.end(), [](ElementType* element) {
delete element;
});
ContType<ElementType*, Alloc> empty{};
container.swap(empty);
}
Of course such an implementation would only work for a container holding pointers to objects.
To conclude, releasing the underlying memory while removing elements is not possible with std::vector.
Question 2
No it's not, it very common to swap std::list for std::vector and vice versa, so using a template deleter would not break client code when a change actually happens.
ptr_vector
. – Jerry Coffin 5 hours ago