使用向量析构函数时出现奇怪的错误



因此,当我不调用向量类的析构函数时,我的代码运行良好。但当我调用向量析构函数时,它会出错,我的向量也会出错。有人能向我解释一下原因吗?据我所知,添加析构函数行应该没有任何区别,因为我只是在使用完它们后释放对象。如果有帮助的话,我会在geekforgeks ide上在线编译。

#include <iostream>
#include <vector>
using namespace std;
//Function that converts from base 10 to another base given by user input
//And results are stored in the vector
int getRepresent(vector<int> &vec, int base, int num) {
if (num < base) {
vec.push_back(num);
return 1;
}
vec.push_back(num % base);
return 1 + getRepresent(vec, base, num / base);
}
//Compute the sum of squares of each digit
int computeSsd(int base, int num) {
vector<int> vec;
int len = getRepresent(vec, base, num);
int i;
int sum = 0;
for (i = 0; i < len; i++) {
sum += vec[i] * vec[i];
}
/*
for (auto x: vec) {
cout << x <<' ';
}
vec.~vector(); //the weird part that cause my vector to change once i add this line
*/
return sum;
}
int main() {
int size;
int i;
cin >> size;
for (i = 0; i < size; i++) {
int display;
int base;
int num;
cin >> display >> base >> num;
int ssd = computeSsd(base, num);
cout << display << ' ' << ssd << 'n';
}
return 0;
}

在这种情况下,您不应该自己调用数据结构*

当对象超出范围时,它将被自动调用。

发生的事情是,您自己调用了析构函数,然后当对象超出范围时,析构函数会自动再次调用,从而调用未定义行为(UB(!想想看,当析构函数被自动调用时,对象就已经被析构函数了!


*手动调用析构函数总是设计不好的标志吗

最新更新