An exercise that Stroustrup wants the reader to do is understand the output of the following program.
#include "../../std_lib_facilities.h"
struct X {
int val;
void out(const string& s, int nv) {
cerr << this << "->" << s << ":" << val << "(" << nv << ")\n";
}
X() {
out("X()", 0);
val = 0;
}
X(int v) {
out("X(int)", v);
val = v;
}
X(const X& x) {
out("X(X&)", x.val);
val = x.val;
}
X& operator = (const X&a) {
out("X::operator = ()", a.val);
val = a.val;
return *this;
}
~X() {
out("~X()", 0);
}
};
X glob(2);
X copy(X a) {return a;}
X copy2(X a) {
X aa = a;
return aa;
}
X& ref_to(X& a) {return a;}
X* make(int i) {
X a(i);
return new X(a);
}
struct XX {
X a;
X b;
};
int main ()
{
X loc(4);
X loc2 = loc;
loc = X(5);
loc2 = copy(loc);
loc2 = copy2(loc);
X loc3(6);
X& r = ref_to(loc);
delete make(7);
delete make(8);
vector<X> v(4);
XX loc4;
X* p = new X(9);
delete p;
X* pp = new X[5];
delete[] pp;
keep_window_open();
return 0;
}
I don't understand this program. It is supposed to have different types of constructors and destructors, variables created and variables destroyed. It prints out whenever a variable is created or destroyed. I don't understand the output. It is a series of memory addresses with an X or an ~X after it. I understand the allocation of memory and the freeing of memory. I assume the net use of memory is zero, representing no memory leak. I can't follow what is going on. I can't cut and paste the output because it is in the console window, but here is a bit of it.
004241A0->X(int):0(2)
0012FF54->X(int):-858993460(4)
0012FF48->X(X&):-858993460(4)
0012FF54->X::operator = ():5(4)
0012FD30->X(X&):969884377(5)
0012FD30->~X():(5)
What does all this mean? Are there tutorials that explain this? Stroustrup has sort of thrown us in the water and left us on our own to find a way to swim.