jud*_*rke 1 c++ templates destructor
在我下面的测试用例中,我很困惑为什么析构函数似乎没有被调用,即使我明确地调用它.我注意到只有在模板类型是指针时才会发生这种情况.
代码(内存泄漏,但我试图让最小的例子成为可能)
#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;
}
Run Code Online (Sandbox Code Playgroud)
产量
Non-pointer test
A DestructorA DestructorA DestructorA DestructorA Destructor
Pointer test
Run Code Online (Sandbox Code Playgroud)
运行示例:https://ideone.com/DB70tF
析构函数被调用.这不是你想到的析构函数.基本上,你有这个:
int main() {
using T = A*;
T* arr = new T[1];
arr[0]->~T();
}
Run Code Online (Sandbox Code Playgroud)
但T是A*,这样的析构函数您的电话是指针的析构函数-这是微不足道的-不是你的类的析构函数.在任何时候你的TemplateTest<A*> pt对象实际上都不会创建任何实例A- 只有实例A*.