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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With