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
This solution is based on Nicol Bolas answer:
struct FdDeleter
{
typedef int pointer;
void operator()(int fd)
{
::close(fd);
}
};
typedef std::unique_ptr UniqueFd;
It's short, but you have to avoid to compare UniqueFd instance with nullptr and use it as boolean expression:
UniqueFd fd(-1, FdDeleter()); //correct
//UniqueFd fd(nullptr, FdDeleter()); //compiler error
if (fd.get() != -1) //correct
{
std::cout << "Ok: it is not printed" << std::endl;
}
if (fd) //incorrect, avoid
{
std::cout << "Problem: it is printed" << std::endl;
}
if (fd != nullptr) //incorrect, avoid
{
std::cout << "Problem: it is printed" << std::endl;
}
return 1;