#A RAII wrapping utility

15 messages · Page 1 of 1 (latest)

clever kraken
#

I've created a thing. The motivation of the thing is to provide ergonomics that std::unique_ptr falls short of:

void foo() {
    auto file = raii_wrap(fopen("whatever.txt", "w"), [] (FILE* ptr) { fclose(ptr); });
    fprintf(file, "hello world");
}

I'm also using c++11 so I don't have things like make_unique that might make it nicer. And without CTAD too it's a bit of a pain.

Implementation below:

template<
    typename T,
    typename D,
    typename std::enable_if<
        std::is_same<decltype(std::declval<D>()(std::declval<T>())), void>::value, int
    >::type = 0
>
class raii_wrapper {
    T obj;
    optional<D> deleter;
public:
    raii_wrapper(T&& obj, D deleter) : obj(std::move(obj)), deleter(deleter) {}
    raii_wrapper(raii_wrapper&& other) : obj(std::move(other.obj)), deleter(other.deleter) {
        other.deleter = nullopt;
    }
    raii_wrapper(const raii_wrapper&) = delete;
    raii_wrapper& operator=(raii_wrapper&&) = delete;
    raii_wrapper& operator=(const raii_wrapper&) = delete;
    ~raii_wrapper() {
        if(deleter) {
            deleter.unwrap()(obj);
        }
    }
    operator T&() {
        return obj;
    }
    operator const T&() const {
        return obj;
    }
};

template<
    typename T,
    typename D,
    typename std::enable_if<
        std::is_same<decltype(std::declval<D>()(std::declval<T>())), void>::value, int
    >::type = 0
>
raii_wrapper<T, D> raii_wrap(T&& obj, D deleter) {
    return {std::move(obj), deleter};
}

https://godbolt.org/z/zfb913nz4

ebon current
#

fwiw this is what unique_resource aimed to do

#

I've personally found these things to never really work out, the benefit never catches up with the cost, there's always another bit of customizability you need

#

just my 0.02

clever kraken
#

Thanks @ebon current

#

Cool to know about unique_resource

ebon current
#

btw

#

http://CppCon.org

Presentation Slides, PDFs, Source Code and other presenter materials are available at: https://github.com/CppCon/CppCon2018

C++ major benefit is its deterministic lifetime model of variables and values. This lead to the RAII (resource-acquisition is initialization) idiom that is essential for resource safety and less leakag...

▶ Play video
#

i was at this cppcon talk

#

and like, as the talk progressed and I saw why unique_resource had been through like 10 revisions

#

my horror slowly increased

#

you'll see why

#

(you can also see me ask a question at the very end lol)

clever kraken
#

Thanks so much

#

I'll give it a watch 🙂