so I'm starting to learn c++ and got around pointers, constructors, destructors, allocation, heap/stack memory.
I have already figured out that local variables created inside functions are allocated on the stack and destructed (or deleted?) after the function return, unless we allocate it on the heap using new
and thus being able to return a pointer to it.
My question is: why is Teest class desctructor not called on this code example after go()
returns?
#include <iostream>
using namespace std;
class Teest {
public:
Teest() {
cout << "Constructed " << ++c << endl;
}
Teest(const Teest&) {
cout << "copy constructor" << endl;
};
Teest& operator=(const Teest&) {
cout << "= operator" << endl;
}
~Teest() {
cout << "Destructed" << endl;
}
void pp() {
cout << "print " << c << endl;
}
int a;
static int c;
};
int Teest::c = 0;
Teest go() {
Teest t;
return t;
}
int main() {
ios::sync_with_stdio(0);
int c;
Teest t = go();
t.a = 3;
cout << t.a << endl;
getchar();
return 0;
}
The output of the above code is:
Constructed 1;
3