c++ - I am losing control and unable to Debug -
class base { private: int nid; friend int fndeletebase(base* base); public: base( int baseid):nid(baseid) { cout << "base constructed value" << endl; } base () : nid(5){cout << "base constructed without value" << endl; } ~base() { cout << "base class object killed " << endl; } }; int fndeletebase(base* base) // line 1 { delete base; // line 2 - important cout << "base object deleted " << endl; return (1); } int main() { base abase; // line 3 try { int = fndeletebase(&abase); // line 4 } catch(...) { cout << "exception handled " << endl; } return (0); }
the above code snippet debugging. unable step @ line 2 deleting base object. try step or run on line 2, control goes , have kill debugging or execution
the output is:
base constructed (any of construction valid) base class object killed
however works fine , if line 3 changed base * abase = new base();
. output on console is:
base constructed (any of construction valid) base class object killed base object deleted
can share technical details behind two?
you should only use delete
on pointers constructed using new
(or pointers assigned other pointers constructed using new
), no exceptions (that know of).
using delete
on else (which happens in first case, since parameter of fndeletebase
pointer base abase
, not pointer , there no new
keyword there) results in undefined behaviour.
explaining compiler won't helpful as, undefined behaviour, can differ compiler compiler. , should avoided @ costs.
Comments
Post a Comment