Using unique_ptr to control a file descriptor

前端 未结 9 2092
無奈伤痛
無奈伤痛 2020-12-10 05:29

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

9条回答
  •  抹茶落季
    2020-12-10 05:35

    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;
    

提交回复
热议问题