+ 1
Can't have custom delete for unique_ptr ?
Hi Refer below code : https://code.sololearn.com/cA177A25a25A/?ref=app Don't we have option to do custom deleter for unique_ptr ?
6 Answers
+ 4
You can, but unlike std::shared_ptr you put the custom deleter in the template for std::unique_ptr like:
std::unique_ptr<int, customDeleter> up( new int[6] );
Btw, std::unique_ptr<int[]> up( new int[6] ) also works if you need delete[] judging by the comment.
+ 3
No idea why the mechanic is different between the two.
I should also clarify that using shared_ptr with arrays before C++17 does not call the correct delete[] on destruction, just for unique_ptr, but it does since C++17.
So you would need your custom deleter in that case.
I don't see a reason to use a custom deleter other than that just to delete a resource allocated by new.
You can use smart pointers to manage resources other than dynamic memory, in those cases you need to provide a custom deleter because a delete wouldn't work, the resource may or may not need to be deleted.
For example resources from the windows api often require deallocation through special functions like a HANDLE.
Instead of doing.
HANDLE h = getCurrentThread();
CloseHandle( h );
You would do:
struct HandleDeleter{
using pointer = HANDLE;
void operator()( pointer handle ) {
if( handle != INVALID_HANDLE_VALUE )
CloseHandle( handle );
}
};
std::unique_ptr<HANDLE, HandleDeleter> h( getCurrentThread() );
+ 2
I ran out of space on the previous post, but the 'using pointer' determines the type that the smart pointer uses internally, if provided, this to allow stack allocated variables.
So no need for a delete here.
0
Thanks a lot Dennis ..specially for clearing belief of delete[] using int[]
0
Also a query on why unique_ptr and shared_ptr is having different mechanism for custom delete...any particular reason or just implemented that way in c++?
And major confusion is now on usage of custom delete as [] also is handled automatically by normal deleter... Is it good to take care of delete even when we choose smart pointer to get rid of memory management ? Any use case of custom delete ?
0
Thanks a lot for detailed and clear answer... Many thanks