C ++ calls the destructor of a nested class template

Suppose I have an x ​​variable of type std :: vector :: iterator that was assigned (for other reasons) with a new placement, for example

new((void*)&x) std::vector<int>::iterator(); 

How can one call its destructor in a standard way? Performance

 x.std::vector<int>::iterator::~iterator(); 

for example, works in gcc but not clang.

+7
c ++ destructor templates nested-class
source share
1 answer

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(); // where x is an iterator 

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 .

+1
source share

All Articles