【发布时间】:2019-05-04 13:10:43
【问题描述】:
所以当我不调用向量类的析构函数时,我的代码可以正常工作。但是当我调用向量析构函数时,它会出错,我的向量也会出错。谁能向我解释为什么?据我了解,添加析构函数行不应该有任何区别,因为我只是在使用完成后释放对象。如果有帮助,我会在 geekforgeeks 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,因为它发生在不存在的对象上。
-
所以我不应该在 C++ 中调用析构函数?
-
真的,正如副本告诉你的那样(很失望 C++ 黄金标签回答了这个问题,而不是标记副本)。
-
析构函数的全部意义在于您不必自己调用它们,它们会自动调用。否则何必大惊小怪?如果你必须自己调用它们,它们只是普通的方法。
标签: c++ oop vector destructor