1

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);
}

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • I hope this code is not from a test. The `delete p` is **wrong**. That should have been a `delete[]`. – MSalters Aug 12 '22 at 11:02
  • Also see [rule of three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – Jason Aug 12 '22 at 11:02
  • @JasonLiam: The Rule of Three is relevant here, but it does not answer the question. – MSalters Aug 12 '22 at 11:08
  • @MSalters Ok, I've added more dupes that explain what happens when we pass argument by value. – Jason Aug 12 '22 at 11:08
  • I think I found a more direct duplicate: https://stackoverflow.com/questions/25968902/destructor-called-when-objects-are-passed-by-value – MSalters Aug 12 '22 at 11:11

1 Answers1

0

Every time f(A a) returns, the parameter a used in the call is destroyed.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • So every time the function is called it creates a copy and releases p at the end of the block? –  Aug 12 '22 at 11:07
  • 1
    @yoavlv12: Indeed, it releases `a.p`. But that is a direct copy of either `a1.p` or `a2.p`, so you release the memory of **another** object. That's why Jason Liam pointed out the Rule of Three. `class A` needs a copy constructor (or better. a `std::vector` - that would have solved all the problems here) – MSalters Aug 12 '22 at 11:10