Boost logo

Boost :

From: Bruno Martínez (bruno.uy_at_[hidden])
Date: 2023-12-04 19:38:31


Hi,

unique_ptr can emulate unique_resource:

    template<auto nullvalue, auto delete_>
    class unique
    {
        using T = decltype(nullvalue);

        struct generic_delete
        {
            class pointer
            {
                T t;
            public:
                pointer(T t) : t(t) {}
                pointer(std::nullptr_t = nullptr) : t(nullvalue) { }
                explicit operator bool() { return t != nullvalue; }
                friend bool operator ==(pointer lhs, pointer rhs) {
return lhs.t == rhs.t; }
                friend bool operator !=(pointer lhs, pointer rhs) {
return lhs.t != rhs.t; }
                operator T() { return t; }
            };

            void operator()(T p)
            {
                delete_(p);
            }
        };
    public:
        using type = std::unique_ptr<struct not_used, generic_delete>;
    };

    int main()
    {
        using unique_fd = unique<-1, close>::type;
        static_assert(sizeof(unique_fd) == sizeof(int), "bloated unique_fd");
        unique_fd fd1(open("fd.txt", O_WRONLY | O_CREAT | O_TRUNC));
        write(fd1.get(), "hello\n", 6);
    }

The std papers say

    While std::unique_ptr can be tweaked by using a custom deleter
type to almost a
perfect handler for resources, it is awkward to use for handle types
that are not pointers.

But what's the awkwardness?

Kind regards,
Bruno


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk