-1

So my code works fine when I do not call the destructor of the vector class. But it bugs out and my vector bugs out when I call the vector destructor. Can anyone explain to me why? From what I understand, adding the destructor line should not make any difference as I am just freeing the object once I used finished them. I'm compiling it online on the geekforgeeks ide if it helps.

#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;
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    The destructor is called automatically when the class goes out of scope. Calling it a first time causes undefined behavior. – Matthieu Brucher Dec 03 '18 at 09:03
  • 2
    More precisely, the second (automatic) call causes UB, since it happens on a non-existent object. – HolyBlackCat Dec 03 '18 at 09:04
  • So i should not call a destructor in C++? – AmateurCoder Dec 03 '18 at 09:06
  • Really, as the duplicate tells you (disappointed that a C++ gold tag answers this instead of tagging the duplicate). – Matthieu Brucher Dec 03 '18 at 09:11
  • The whole point of destructors is that you *don't* have to call them yourself, they get called automatically. Otherwise why all the fuss? If you had to call them yourself they'd just be ordinary methods. – john Dec 03 '18 at 09:13

1 Answers1

1

You shouldn't call the dsestructor yourself in this case*.

It will be called automatically, when the object goes out of scope.

What happened, is that you called the destructor yourself, then the destructor was called again automatically when the object went out of scope, which invoked Undefined Behavior (UB)! Think about it, when the destructor is called automatically, the object is already destructed!


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

gsamaras
  • 71,951
  • 46
  • 188
  • 305