In my test case below I am puzzled as to why the destructor does not seem to be get called even though I am explicitly calling it. I noticed this only happens when the template type is a pointer.
Code (with memory leaks, but I tried to make the smallest example possible)
#include <iostream>
using namespace std;
class A {
public:
A() {}
~A() { cout << "A Destructor"; }
};
template<typename Type>
class TemplateTest {
protected:
Type* start;
Type* end;
Type* iter;
public:
void Generate(unsigned int count) {
start = new Type[count];
end = start + count;
iter = start;
}
void DestroyAll() {
for(; start < end; ++start) {
(*start).~Type();
}
}
void Push(Type val) {
*iter = val;
iter++;
}
};
int main() {
cout << "Non-pointer test" << endl;
TemplateTest<A> npt;
npt.Generate(5);
npt.DestroyAll();
cout << "\nPointer test";
TemplateTest<A*> pt;
pt.Generate(5);
pt.Push(new A());
pt.DestroyAll();
return 0;
}
Output
Non-pointer test
A DestructorA DestructorA DestructorA DestructorA Destructor
Pointer test
Running example: https://ideone.com/DB70tF
The destructor is getting called. It's just not the destructor you're thinking of. Basically, you have this:
int main() {
using T = A*;
T* arr = new T[1];
arr[0]->~T();
}
But T
is A*
, so the destructor your calling is the pointer destructor - which is trivial - not your class's destructor. At no point does your TemplateTest<A*> pt
object actually create any instances of A
- only instances of A*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.