But this means, before the .clear()
, the container is corrupted.
The container is not corrupted. It stores char*
s, which can be thought of as numerical addresses at which text might be stored. If valid text is no longer stored at those addresses, that's perfectly fine as long as no attempt is made to follow/dereference the pointer to access that memory. unordered_map<char*>
treats the char*
as values/numbers and is effectively unaware that they might point at anything - it will never dereference the pointers even if the container was resized/rehashed. And anyway, the container will never resize unless you do more insertions that cross the max_load_factor()
.
What it does mean is that you've - momentarily - got a container full of dangling pointers. That's not undefined behaviour - it's perfectly fine, the same way that this is fine:
{
char* p = strdup("boo");
free(p);
}
There, p is a dangling pointer after the free()
, but nothing nasty happens as the scope exists - there is no hidden/implicit destructor to run for char*
objects.
That said, it would be better to use RAII semantics - a type wrapping the char*
that will free it in the destructor: this answer shows one way to do that with std::unique_ptr
.