+ 1
How to avoid memory Leak when Using pointers?
4 Antworten
+ 4
There are many pointer wrapper classes.
2 examples:
There is a unique_ptr which deletes its underlying element in its deconstructor. unique_ptr is not slower than a raw pointer which is deleted by hand.
There is also a shared_ptr. The underlying element of a shared_ptr is just deleted if no other shared_ptr points to it.
But what if you must deal with old C code which uses raw pointers and something like ptr->free()? You creat a ptr_handle class which calls ptr->free() in its deconstructor. It's not slower and this way, you can be sure that ptr doesn't leak.
+ 2
Rahul thank you but can we also assign a NULL Value to the pointer after it has been deleted ?
delete p;
p=NULL
+ 1
Martin Taylor thank you
0
The memory that has been dynamically allocated for a certain purpose must be deallocated as soon as that purpose is over,in order to prevent memory leak.