1

For an object, its destructor is called when it goes out of scope. Here's my program:

#include <iostream>
using namespace std;

class A {
 public:
  A() {}
  ~A() { cout << "A's destructor called!" << endl; }
};

class B {
 public:
  B() = delete;
  B(int x_) {}
  ~B() { cout << "B's destructor called!" << endl; }
};

void func_a() { A a(); }

void func_b() { B b(1); }

int main() {
  cout << "A" << endl;
  func_a();
  cout << "B" << endl;
  func_b();
  cout << "bye" << endl;
  return 0;
}

I thought either A's or B's destructor would be called. But the fact is only B's destructor called. I'm very confused. Is this because of the storage way of the class? Output:

A
B
B's destructor called!
bye
Snoopy
  • 55
  • 1
  • 5
  • 1
    Ah, yes, the [most vexing parse](https://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets) – Yksisarvinen Dec 18 '20 at 06:34

1 Answers1

4

Change this

void func_a() { A a(); }

to this

void func_a() { A a; }

In your code a is a function declaration, not an object.

Put a cout << statement in the constructor too. You will see that the constructor for A isn't called either.

john
  • 85,011
  • 4
  • 57
  • 81