class Titi {
public:
int* pMyInts;
Titi() {
pMyInts = newint[2];
}
Titi(int a0, int a1) {
Titi();
pMyInts[0] = a0;
pMyInts[1] = a1;
}
~Titi() {
delete [] pMyInts;
}
};
int main(int argc, constchar *argv[]) {
cout << "Test a constructor with parameters that call a custom constructor with no parameters but that has the charge to allocate memory for pointers on arrays with new" << endl;
Titi t(5,7);
cout << "\tTiti t(5,7) = " << t.pMyInts[0] << " " << t.pMyInts[1] << endl;
return 0;
}
At runtime, the first cout is printed and nothing else.
At debug, I can see that when I exit Titi(), pMyInts loose its value. What explains this code fails. But why does it loose its value ? I cannot figure out what I do wrong.
you create unnamed temporary object which will be deleted in the same statement after ; So the next code has undefined behavior because you did not allocate memory for pMyInts.
this code *this = Test(); can work only then the compiler uses optimization and does not create a temporary object Test(). Otherwise destructor will be called and it will delete the pointer. So in general this code has undefined behavior.