I was surprised to find out the vector::erase move elements on calling erase . I thought it would swap the last element with the “to-be-deleted” element and reduce the size by one. My first reaction was : “let’s extend std::vector and over-ride erase()” . But I found in many threads like ” Is there any real risk to deriving from the C++ STL containers? “, that it can cause memory leaks. But, I am not adding any new data member to vector. So there is no additional memory to be freed. Is there still a risk?
Some suggest that we should prefer composition over inheritance. I can’t make sense of this advice in this context. Why should I waste my time in the “mechanical” task of wrapping every function of the otherwise wonderful std::vector class.? Inheritance indeed makes the most sense for this task – or am I missing something?
Delicate issue. The first guideline you’re breaking is: “Inheritance is not for code reuse“. The second is: “Don’t inherit from standard library containers”.
But: If you can guarantee, that nobody will ever use your
unordered_vector<T>as avector<T>you’re good. However, if somebody does, the results may be undefined and/or horrible, regardless of how many members you have (it may seem to work perfectly but nevertheless be undefined behaviour!).You could use
privateinheritance, but that would not free you from writing wrappers or pulling member functions in with lots ofusingstatements, which would almost be as much code as composition (a bit less, though).Edit: What I mean with
usingstatements is this:You could do this with all member functions of
std::vector. As you can seeDerivedis significantly less code thanComposed.