C++ Destructor Conventions -
i see lot of code example below in c++, recommended convention:
class foo { public: foo() { bar = new int[100]; size = 100; } // ... copy/assignment stuff ... ~foo() { if (bar) // <--- needed? { delete[] bar; bar = nullptr; // <--- needed? } size = 0; // <--- needed? } private: int* bar; int size; }; to me, 3 statements if (bar) { ... }, bar = nullptr;, , size = 0; redundant 2 reasons:
delete nullptr;prefectly safe, , doesn't anything.- if object destroyed , memory released, shouldn't worry safety set
barnullptr,size0.
are these justifications correct? these statement redundant? if so, why people keep using , suggesting them? see potential problems solved keeping convention.
you're right, aren't needed , compilers optimize them away anyway.
however - reason people spot out problems. example, don't set pointer null. object destroyed, incorrectly attempt access (what once was) pointer. since runtime not clear it, you'll still see valid there. valuable debugging, , it's still undefined behavior, pays off.
Comments
Post a Comment