Why is the destructor called three times?

Input:

#include <iostream>
using namespace std;
class SimpleClass
{
    public:

    SimpleClass()
    {
        cout<<"SimpleClass Constructor\n";
    }
    virtual ~SimpleClass()
    {
        cout<<"SimpleClass destructor\n";
    }
};
int main()
{
    SimpleClass a;    
    SimpleClass lol = a;

    SimpleClass b;
    SimpleClass * lol2 = &b;
}

Output:

SimpleClass Constructor
SimpleClass Constructor
SimpleClass destructor
SimpleClass destructor
SimpleClass destructor

I am confused why the destructor is called 3 times.

The constructor is called only twice !!!!

+4
source share
7 answers

The destructor is called three times, for a, loland b.
In your case, aand bare created using default constructor. However, note that lolcreated usingcopy constructor

+10
source

Since there are only 3 objects of the SimpleClass class, but your constructor is called only 2 times:

  • 1st object a, calls your constructor;
  • 2nd is lol, a ( , );
  • 3rd - b, .

, lol2 - b, .

"", "deconstructor";)

+6

3 a, lol b. , ( lol), .

+5

a, lol b.

, /, . this, .

+3
  SimpleClass lol = a;    //calls the default copy constructor which you have not defined

, .

+2

a, lol b.

, main(), , .

0

.

0

All Articles