All standard (and standard) iterators follow the Iterator concept , which should be Destructible . Thus, it is enough to simply call the iterator destructor in the same way as in any other (non-trivial) types built with a new location.
x.~iterator_type();
Note that if you are referencing an iterator using a pointer, you must use the -> operator:
#include <vector> int main() { auto buffer = new char[sizeof(std::vector<int>::iterator)]; auto iterator = new((void*)buffer) std::vector<int>::iterator(); iterator->std::vector<int>::iterator::~iterator(); delete[] buffer; }
DIRECT EXAMPLE (GCC)
UPDATE: The Clan seems to have some compilation issues (I believe this is up to standard). You can make a round around this by providing indirection when calling the destructor:
#include <vector> template<typename T> void call_destructor(T* x) { x->~T(); } int main() { auto buffer = new char[sizeof(std::vector<int>::iterator)]; auto iterator = new((void*)buffer) std::vector<int>::iterator(); //iterator->std::vector<int>::iterator::~iterator(); call_destructor(iterator); delete[] buffer; }
DIRECT EXAMPLE (clang)
UPDATE:. This is a bug in clang: http://llvm.org/bugs/show_bug.cgi?id=12350 . See the comment by Dieter Luke .
I am very sorry for all of you, especially the OP, for this mess .
Mark garcia
source share