std::unique_ptr for C functions that need free

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

    The original question (and hvd's answer) introduce a per-pointer overhead, so such a unique_ptr is twice the size than one derived with std::make_unique. In addition, I would formulate the decltype directly:

    std::unique_ptr
        t_copy { strdup(t), &std::free };
    

    If one has many of those C-API-derived pointers that extra space can be a burden hindering adoption of safe C++ RAII for C++ code wrapping existing POSIX style APIs requiring to be free()d. Another problem that can arise, is when you use char const in the above situation, you get a compile error, because you can not automatically convert a char const * to the Parameter type of free(void *).

    I suggest to use a dedicated deleter type, not one built on the fly, so that the space overhead goes away and the required const_cast is also not a problem. A template alias then can easily be used to wrap C-API-derived pointers:

    struct free_deleter{
        template 
        void operator()(T *p) const {
            std::free(const_cast*>(p));
        }
    };
    template 
    using unique_C_ptr=std::unique_ptr;
    static_assert(sizeof(char *)==
                  sizeof(unique_C_ptr),""); // ensure no overhead
    

    The example now becomes

    unique_C_ptr t_copy { strdup(t) };
    

    I will suggest that that mechanism should be made available in the C++ Core Guidelines support library ( maybe with a better naming ), so it can be made available for code bases transitioning to modern C++ ( success open ).

提交回复
热议问题