+ 2
Need for custom deleter
Hello I am using shared pointer. If it is for int or double, we don't need to worry as it is inbuilt type. For class , we may have resources like heap allocation or text file opening. This is done in constructor and destructor will free both these resources. Make shared also calls destructor. So I m not getting point of having custom deleter for shared pointer.. why custom deleter is required ? If I am not wrong , [] array of smart pointer was not releasing memory properly till C++ 17 but now it is also solved and calls delete [] instead of delete Having said this all , do we literally need custom deleter now a days ?
2 Answers
+ 3
>Volodymyr Melnychenko
It seems that the first practicing software developer signed up for Sololearn, not a student who is just learning.
+ 1
Class destructor and custom deleter both exist for different uses. I agree with you that in most cases the custom deleter concept seems superfluous and redundant, indeed, in my practice I rarely use it.
Destructor is invoked always no matter where the class is used. Custom deleter on the other hand is invoked only to clean up a smart pointer and can be different in different parts of your code.
While thinking about it I see two reasons to use custom deleters. First, you use it when the underlying class does not have a destructor at all, that's the case with plain C structures, for example.
Second, when you need to do something more than just destruct the object, say you want to update other structures, send events or simply log for debug purposes.