Skip to content

Instantly share code, notes, and snippets.

@sawaYch
Last active November 4, 2018 15:39
Show Gist options
  • Save sawaYch/1a192fb73e923fedb35209b812063b3b to your computer and use it in GitHub Desktop.
Save sawaYch/1a192fb73e923fedb35209b812063b3b to your computer and use it in GitHub Desktop.
Something you need to care about in modern C++

Vector, Beware of erase()

If you are using this style and when you erase() items in vector, be careful dont perform ++iterator.
Since the pointer to the item that you erase(), it already release, so the pointer target will become unknown,
and causing undefined behaviour if the iteration keep going.
It is possible cause the vector iteration out-of-bound.

template <class T>
void Container<T>::removeValue(T *value, bool deletePointer)
{
	for (iterator i = values.begin(); i != values.end(); ) {
		// remove the input value from the container
		if ((*i) == value) {
			// check whether free the memory allocated to value or not.
			if (deletePointer) {
				delete valuse;
				values.erase(i);
			} else {
				values.erase(i);
			}
		}else{
	    		++i;     // only update iterator when current iterator is not erased.
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment