c++ - Should pointers to "raw" resources be zeroed in destructors? -
c++ - Should pointers to "raw" resources be zeroed in destructors? -
when wrap "raw" resources in c++ class, in destructor code release allocated resource(s), without paying attending additional steps zeroing out pointers, etc. e.g.:
class file { public: ... ~file() { if (m_file != null) fclose(m_file); } private: file * m_file; };
i wonder if code style contains potential bug: i.e. is possible destructor called more once? in case, right thing in destructor clear pointers avoid double/multiple destructions:
~file() { if (m_file != null) { fclose(m_file); m_file = null; // avoid double destruction } }
a similar illustration made heap-allocated memory: if m_ptr
pointer memory allocated new[]
, next destructor code ok?
// in destructor: delete [] m_ptr;
or should pointer cleared, too, avoid double destruction?
// in destructor: delete [] m_ptr; m_ptr = null; // avoid double destruction
no. useful if have close()
function or like:
void close() { if (m_file != null) { fclose(m_file); m_file = null; } } ~file() { close(); }
this way, close()
function idempotent (you can phone call many times want), , avoid 1 test in destructor.
but since destructors in c++ can called once, assigning null pointers there pointless.
unless, of course, debuggin-purposes, particularly if suspect double-delete.
c++ destructor raii
Comments
Post a Comment