c++ - Memory management pointers -


this question has answer here:

i saw common practice of deleting pointer amd making null in destructor if no memory allocated pointer on heap. consider below c++ code:

dummy.h

class dummy {      int* a; } 

dummy.cpp

  dummy::dummy():a(null)    { cout<<inside const"; }     dummy::~dummy()   {     if(a!=null)     {       delete a;       = null;     }   }    bool func()   {      = func1();   } 

in above code although memory not allocated on heap, deleted. should not lead memory leak?

making null pointless, since it's destroyed.

your code isn't deleting if it's null, due if (a!=null). however, that's pointless: applying delete null pointer nothing, can reduce destructor unconditional delete a; (assuming know it's either null, or points object created new).

you need make sure class either isn't copyable, or has valid copy semantics, per rule of three; otherwise, copying object lead deleting same memory twice, not allowed.

better still, stop juggling pointers, , use smart pointers, containers , other raii types make life simpler.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -