Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the program not call the destructor in c++?

Tags:

c++

destructor

So here's the code:

#include <iostream>

using namespace std;

class C {
public:
    C() {i = 6; cout << "A:" << i << endl;}

    C(int i0) {i = i0; cout << "B:" << i << endl;}

    ~C() {cout << "C:" << i << endl;}
private:
    int i;
};

int main(int argc, char* argv[]) {
    cout << "X" << endl;
    C *c = new C;
    cout << "Y" << endl;
}

For some reason the output for that code is

X
A:6
Y

And for some reason the destructor (C:6) is never called once you reach the end of the code. Why is that? Also this code does call the destructor:

#include <iostream>

using namespace std;

class C {
public:
    C() {i = 0; cout << "A:" << i << endl;}

    C(int i0) {i = i0; cout << "B:" << i << endl;}

    ~C() {cout << "C:" << i << endl;}
private:
    int i;
};

int main(int argc, char* argv[]) {
    cout << "X" << endl;
    C c;
    cout << "Y" << endl;
}
like image 970
David Rolfe Avatar asked Dec 30 '25 05:12

David Rolfe


1 Answers

Because you forgot to write

delete c;

If you just go on in your program without deleting a variable instantiated with new you will cause a memory leak.

Edit, since you edited your question:

If you write something like

C c;
C c{1};
C c = C{1};

you create a variable with automatic storage duration. It will run out of scope once the function it is declared in exits (or more precise: once the block it is declared in exits). In this case the constructor is called automatically.

If you write

C* c = new C{};

you create a pointer to a (new) C. The pointer itself has automatic storage duration, which means c will run out of scope as well. But the pointer only holds the adress of the object of type C. And this object is only deleted if you call delete c;. If you don't call delete, your program "forgets" the address of the object but it does not free the memory or destroy the object. That's a memory leak.
However once your program ends, all memory is freed (without calling destructors), so in your small example you wont notice.

like image 193
Anedar Avatar answered Jan 01 '26 20:01

Anedar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!