Dzamba
Dzamba

Reputation: 197

Why is there more destructor calls than constructor calls

I was testing out the following code and what confused me is that there is more destructor calls than constructor calls:

#include <iostream>

struct A {
    A() { std::cout << 1; }
    A(int) { std::cout << 7; }
    ~A() { std::cout << 5; }
};

struct B {
    B() { std::cout << 2; }
    B(int) { std::cout << 9; }
    ~B() {std::cout << 3;}
};

struct C {
    B b;
    A a1;
    A a2;
    C() : a1(3){
        b = 3;
        a2 = 7;
    }
};

int main(){
    C c;
    return 0;
}

The output is like follows:

B()  A(int) A() B(int) ~B() A(int) ~A() ~A() ~A() ~B() 
 2     7     1    9      3     7     5    5    5    3

My guess is that on the lines b = 3 and a2 = 7, 3 and 7 must be implicitly converted to B and A and when they get copied into b and a2, they get destroyed.

Is this correct or is something else going on here?

Upvotes: 3

Views: 299

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596041

You are not logging the copy constructors and copy assignment operators, eg:

struct A {
    A() { ... }
    A(int) { ... }
    A(const A&) { ... } // <-- add this
    ~A() { ... }
    A& operator=(const A&) { ...; return *this; } // <-- add this
};

struct B {
    B() { ... }
    B(int) { ... }
    B(const B&) { ... } // <-- add this
    ~B() { ... }
    B& operator=(const B&) { ...; return *this; } // <-- add this
};

But, if you actually count the outputs you have shown, you will see that you ARE seeing matching constructors and destructors. You have 3 A constructor calls and 3 ~A destructor calls. And you have 2 B constructor calls, and 2 ~B destructor calls.

B()         C::b
A(int)      C::a1
A()         C::a2
B(int)      temp
B=          temp -> C::b
~B()        temp
A(int)      temp
A=          temp -> C::a2
~A()        temp
~A()        C::a2
~A()        C::a1
~B()        C::b

Demo

Upvotes: 7

Related Questions