Using unique_ptr to control a file descriptor

前端 未结 9 2095
無奈伤痛
無奈伤痛 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:38

    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);
    

提交回复
热议问题