certificate task /exceptions C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

certificate task /exceptions C++

Hello guys, I have exam task from C++ , what I don't understand class X { public: X(void) { cout << 1; } ~X(void) { cout << 2; } }; X *exec() { X *x = new X(); throw string("0"); return x; } int main(void) { X *x; try { delete exec(); } catch(string &s) { cout << s; } return 0; } Question: nr1. What happens in try{ } branch ? - how is possible to run function exec() using delete operator? This function starts new object after call. How is possible to "delete" unexisting object, before its called. its like "lock the draver with the key inside" nr2. What does it mean X *exec() {body of function} as far as I remmember correct answer should be 102, but, when I compile its 10, it means that destructor isn't called at all.

24th Aug 2019, 12:38 AM
Adam
3 Answers
+ 3
So we know that there is no explicit delete due to the exception being thrown. Agent_I I wanted to know if there is an implicit delete just before the program ends. I.e. is there a clean up of resources upon return from main?
24th Aug 2019, 5:57 AM
Sonic
Sonic - avatar
+ 2
The delete operator only evaluate the return value of the exec function, so the exec function will be executed first and then the delete operator. NB. The delete operator doesn't care whether the object exists or not. The signature of the exec function is a function with the name of exec that returns a pointer to X object. The destructor is not called at all because the delete operator is actually ignored. The exec function throws an exception right after the object creation, so everything else after that, including the delete operator, is not executed, the control will basically jump to the catch block right after the exception is thrown
24th Aug 2019, 1:31 AM
Agent_I
Agent_I - avatar
+ 1
Sonic Normally, the heap will be cleaned up when the program ends. However, for objects with dynamic storage duration (located in the heap), their destructor will only be called using delete expression, even though it will be implicitly deleted when the program ends.
24th Aug 2019, 7:29 AM
Agent_I
Agent_I - avatar