在看《数据结构、算法与应用》这本书的线性表-数组描述时,看到这个函数
template<class T>
void arrayList<T>::erase(int the Index)
{
checkIndex(theIndex);
copy(element + theIndex + 1, element + listSize, element + theIndex);
element[--listSize].~T(); //调用析构函数
}
数组的单个元素能析构吗?
本人在VS2015上试了一下
#include<iostream>
using namespace std;
template<class T>
void test()
{
int* p = new int[10];
for (int i = 0; i < 10; i++)
p[i] = i;
p[9].~T();
cout << p[9]<<endl;
}
int main()
{
test<int>();
return 0;
}
解决方案
15
这个只是调用 析构函数, 并不释放内存. 假如析构函数里面什么也没做, 那就没有什么效果.
而且即使你调用释放了内存, 也并不意味着不能访问这块内存, 或是会得到结果 0. 访问已释放内存的结果是未定义的, 不一定就会出错.
而且即使你调用释放了内存, 也并不意味着不能访问这块内存, 或是会得到结果 0. 访问已释放内存的结果是未定义的, 不一定就会出错.
5
析构不等于会清除其中的内容。
