作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我下面的测试用例中,我很困惑为什么即使我明确地调用了析构函数,它似乎也没有被调用。我注意到只有当模板类型是指针时才会发生这种情况。
代码(有内存泄漏,但我尽量使示例尽可能小)
#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;
}
输出
Non-pointer test
A DestructorA DestructorA DestructorA DestructorA Destructor
Pointer test
最佳答案
正在调用析构函数。它只是不是你想的析构函数。基本上,你有这个:
int main() {
using T = A*;
T* arr = new T[1];
arr[0]->~T();
}
但是T
是A*
,所以你调用的析构函数是 pointer 析构函数——这是微不足道的——而不是你类的析构函数。您的 TemplateTest<A*> pt
绝不会对象实际创建 A
的任何实例- 只有 A*
的实例.
关于c++ - 为什么析构函数在显式调用时不会在模板化指针上被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418792/
我是一名优秀的程序员,十分优秀!