In theory, I should be able to use a custom pointer type and deleter in order to have unique_ptr manage an object that is not a pointer. I tried the following c
I would suggest using shared_ptr rather than unique_ptr to manage the life time of int handles because the shared ownership semantics are usually a better fit, and because the type of the deleter is erased. You need the following helper:
namespace handle_detail
{
template
struct deleter
{
deleter( H h, D d ): h_(h), d_(d) { }
void operator()( H * h ) { (void) d_(h_); }
H h_;
D d_;
};
}
template
std::shared_ptr
make_handle( H h, D d )
{
std::shared_ptr p((H *)0,handle_detail::deleter(h,d));
return std::shared_ptr(
p,
&std::get_deleter >(p)->h_ );
}
To use with a file descriptor:
int fh = open("readme.txt", O_RDONLY); // Check for errors though.
std::shared_ptr f = make_handle(fh, &close);