gpt4 book ai didi

c++ - 为什么析构函数在显式调用时不会在模板化指针上被调用?

转载 作者:行者123 更新时间:2023-11-30 01:14:21 26 4
gpt4 key购买 nike

在我下面的测试用例中,我很困惑为什么即使我明确地调用了析构函数,它似乎也没有被调用。我注意到只有当模板类型是指针时才会发生这种情况。

代码(有内存泄漏,但我尽量使示例尽可能小)

#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

运行示例:https://ideone.com/DB70tF

最佳答案

正在调用析构函数。它只是不是你想的析构函数。基本上,你有这个:

int main() {
using T = A*;
T* arr = new T[1];
arr[0]->~T();
}

但是TA* ,所以你调用的析构函数是 pointer 析构函数——这是微不足道的——而不是你类的析构函数。您的 TemplateTest<A*> pt 绝不会对象实际创建 A 的任何实例- 只有 A* 的实例.

关于c++ - 为什么析构函数在显式调用时不会在模板化指针上被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com