std::unique_ptr for C functions that need free

前端 未结 4 486
攒了一身酷
攒了一身酷 2020-12-01 06:58

Think to a C function that return something that must be freed, for example the POSIX\'s strdup(). I want to use that function in C++11 and avoid a

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 07:57

    Assuming it makes sense, it is possible to use a similar pattern with non-pointers? For example for the POSIX's function open that returns an int?

    Sure, using Howard's Hinnant tutorial on unique_ptr, we can see a motivating example:

    // For open
    #include 
    #include 
    
    // For close
    #include 
    
    // For unique_ptr
    #include 
    
    int main()
    {
        auto handle_deleter = [] (int* handle) {
            close(*handle);
        };
    
        int handle = open("main.cpp", O_RDONLY);
        std::unique_ptr uptr
            { &handle, handle_deleter };
    }
    

    Alternatively you can use a functor instead of a lambda:

    struct close_handler
    {
        void operator()(int* handle) const
        {
            close(*handle);
        }
    };
    
    int main()
    {
        int handle = open("main.cpp", O_RDONLY);
        std::unique_ptr uptr
            { &handle };
    }
    

    The example can be further reduced if we use a typedef and a "factory" function.

    using handle = int;
    using handle_ptr = std::unique_ptr;
    
    template 
    handle_ptr get_file_handle(T&&... args)
    {
        return handle_ptr(new handle{open(std::forward(args)...)});
    }
    
    int main()
    {
        handle_ptr hp = get_file_handle("main.cpp", O_RDONLY);
    }
    

提交回复
热议问题