std::unique_ptr for C functions that need free

前端 未结 4 485
攒了一身酷
攒了一身酷 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:42

    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?

    Yes, it can be done. You need a "pointer" type that satisfies the NullablePointer requirements:

    struct handle_wrapper {
    
        handle_wrapper() noexcept : handle(-1) {}
        explicit handle_wrapper(int h) noexcept : handle(h) {}
        handle_wrapper(std::nullptr_t)  noexcept : handle_wrapper() {}
    
        int operator *() const noexcept { return handle; }
        explicit operator bool() const noexcept { return *this != nullptr; }
    
        friend bool operator!=(const handle_wrapper& a, const handle_wrapper& b) noexcept {
            return a.handle != b.handle;
        }
    
        friend bool operator==(const handle_wrapper& a, const handle_wrapper& b) noexcept {
            return a.handle == b.handle;
        }
    
        int handle;
    };
    

    Note that we use -1 as the null handle value here because that's what open() returns on failure. It's also very easy to templatize this code so that it accepts other handle types and/or invalid values.

    Then

    struct posix_close
    {
        using pointer = handle_wrapper;
        void operator()(pointer fd) const
        {
            close(*fd);
        }
    };
    
    int
    main()
    {
        std::unique_ptr p(handle_wrapper(open("testing", O_CREAT)));
        int fd = *p.get();
    }
    

    Demo.

提交回复
热议问题