【问题标题】:Weird bug when using vector destructor [duplicate]使用矢量析构函数时出现奇怪的错误[重复]
【发布时间】: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


【解决方案1】:

在这种情况下,您不应该自己调用 dsestructor*

当对象超出范围时会自动调用。

发生了什么事,是你自己调用了析构函数,然后当对象超出范围时又自动调用了析构函数,这调用了未定义的行为(UB)!想想看,当自动调用析构函数的时候,对象就已经被销毁了!


*Is calling destructor manually always a sign of bad design?

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2020-07-02
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2013-07-11
    • 2014-11-26
    • 2020-08-30
    相关资源
    最近更新 更多