I'm trying to figure out why in this piece of code, every time the function f() is called, the function calls the destructor and does not reallocate the size of the array
I know if I change it to int f(A & a) { return 2 * a.n; }
it will work, but I still don't understand why it goes into the destructor.
class A {
public:
A(int i = 10) {
n = i;
p = new int[n];
for (int j = 0; j < n; j++) {
p[j] = 0;
}
}
~A() { delete p; }
int n;
int* p;
};
int f(A a) { return 2 * a.n; }
int main() {
A a1(5), a2(5);
cout << 1 << endl;
f(a1);
cout << 2 << endl;
f(a2);
cout << 3 << endl;
f(a1);
cout << 4 << endl;
f(a2);
}