What wrapper class in C++ should I use for automated resource management?

安稳与你 提交于 2019-11-29 03:26:16

Write your own. It's only a few lines of code. It's just such a simple task that it's not worth it to provide a generic reusable version.

struct FileWrapper {
  FileWrapper(...) : h(CreateFile(...)) {}
  ~FileWrapper() { CloseHandle(h); }

private:
  HANDLE h;
};

Think about what a generic version would have to do: It'd have to be parametrizable so you can specify any pair of functions, and any number of arguments to them. Just instantiating such an object would likely take as many lines of code as the above class definition.

Of course, C++0x might tip the balance somewhat with the addition of lambda expressions. Two lambda expressions could easily be passed to a generic wrapper class, so once C++0x supports comes around, we might see such a generic RAII class added to Boost or something.

But at the moment, it's easier to just roll your own whenever you need it.

As for adding reference counting, I'd advise against it. Reference counting is expensive (suddenly your handle has to be dynamically allocated, and reference counters have to be maintained on every assignment), and very hard to get right. It's an area just bursting with subtle race conditions in a threaded environment.

If you do need reference counting, just do something like boost::shared_ptr<FileWrapper>: wrap your custom ad-hoc RAII classes in a shared_ptr.

Essentially, fstream is a good C++ wrapper for file handles. It's part of the standard which means it is portable, well tested, and extensible in an object-oriented manner. For file resources, it is a great concept.

However, fstream only works for files, not for generic handles, i.e. threads, processes, synchronization objects, memory-mapped files, etc.

These wrappers are called ATL.

If your handle is an event or similar, use CHandle class.

If your handle is a file, use CAtlFile derived one, it wraps APIs like CreateFile and ReadFile.

There’re other useful wrappers in ATL, CAtlFileMapping<T> is a RAII wrapper over memory mapped files, CPath wraps shell32 APIs for path handling, and so on.

ATL is large library, but low-level things like files, strings and collections are isolated. You can use them in all Win32 apps. is header only, you don’t need to link with anything, or distribute extra DLLs like MFC or CRT, the code compiles into WinAPI calls and just works.

They were split from MFC in VS2003 or 2005, don’t remember, i.e. Visual Studio 2008 definitely has them. There’s one caveat however, if you’re using a freeware version of VS, it must be 2015 or newer.

Here's one based off the EnsureCleanup code from 'Windows via C/C++': http://www.codeproject.com/KB/cpp/template2003.aspx

MFC has some suitable primitives (look at CFile for example), but not the standard library.

Visual C++ 2008 supports TR1 through the Feature Pack, and TR1 includes shared_ptr. I would use this -- it's a very powerful smart pointer class and can be generalized to do the type of resource management you are asking for.

TR1 is effectively an extension to the Standard. I believe it's still officially "pre-standard", but effectively you can consider it locked down.

I don't think there is anything in the standard library, and I also doubt that shared pointers (as in boost) can be used (since those would expect pointer to HANDLE, not HANDLE).

It shouldn't be hard to write one yourself, following the scope guard idiom (and making use of templates/function pointers etc if you so choose).

template <typename Traits>
class unique_handle
{
    using pointer = typename Traits::pointer;

    pointer m_value;

    auto close() throw() -> void
    {
        if (*this)
        {
            Traits::close(m_value);
        }
    }

public:

    unique_handle(unique_handle const &) = delete;
    auto operator=(unique_handle const &)->unique_handle & = delete;

    explicit unique_handle(pointer value = Traits::invalid()) throw() :
        m_value{ value }
    {
    }

    unique_handle(unique_handle && other) throw() :
        m_value{ other.release() }
    {
    }

    auto operator=(unique_handle && other) throw() -> unique_handle &
    {
        if (this != &other)
        {
            reset(other.release());
        }

        return *this;
    }

    ~unique_handle() throw()
    {
        close();
    }

    explicit operator bool() const throw()
    {
        return m_value != Traits::invalid();
    }

    auto get() const throw() -> pointer
    {
        return m_value;
    }

    auto get_address_of() throw() -> pointer *
    {
        ASSERT(!*this);
        return &m_value;
    }

    auto release() throw() -> pointer
    {
        auto value = m_value;
        m_value = Traits::invalid();
        return value;
    }

    auto reset(pointer value = Traits::invalid()) throw() -> bool
    {
        if (m_value != value)
        {
            close();
            m_value = value;
        }

        return static_cast<bool>(*this);
    }

    auto swap(unique_handle<Traits> & other) throw() -> void
    {
        std::swap(m_value, other.m_value);
    }
};

template <typename Traits>
auto swap(unique_handle<Traits> & left,
    unique_handle<Traits> & right) throw() -> void
{
    left.swap(right);
}

template <typename Traits>
auto operator==(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() == right.get();
}

template <typename Traits>
auto operator!=(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() != right.get();
}

template <typename Traits>
auto operator<(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() < right.get();
}

template <typename Traits>
auto operator>=(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() >= right.get();
}

template <typename Traits>
auto operator>(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() > right.get();
}

template <typename Traits>
auto operator<=(unique_handle<Traits> const & left,
    unique_handle<Traits> const & right) throw() -> bool
{
    return left.get() <= right.get();
}

struct null_handle_traits
{
    using pointer = HANDLE;

    static auto invalid() throw() -> pointer
    {
        return nullptr;
    }

    static auto close(pointer value) throw() -> void
    {
        VERIFY(CloseHandle(value));
    }
};

struct invalid_handle_traits
{
    using pointer = HANDLE;

    static auto invalid() throw() -> pointer
    {
        return INVALID_HANDLE_VALUE;
    }

    static auto close(pointer value) throw() -> void
    {
        VERIFY(CloseHandle(value));
    }
};

using null_handle = unique_handle<null_handle_traits>;
using invalid_handle = unique_handle<invalid_handle_traits>;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!