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

删除回忆录丶 提交于 2019-12-29 05:50:13

问题


I'm a C++ amateur. I'm writing some Win32 API code and there are handles and weirdly compositely allocated objects aplenty. So I was wondering - is there some wrapper class that would make resource management easier?

For example, when I want to load some data I open a file with CreateFile() and get a HANDLE. When I'm done with it, I should call CloseHandle() on it. But for any reasonably complex loading function there will be dozens of possible exit points, not to mention exceptions.

So it would be great if I could wrap the handle in some kind of wrapper class which would automatically call CloseHandle() once execution left the scope. Even better - it could do some reference counting so I can pass it around in and out of other functions, and it would release the resource only when the last reference left scope.

The concept is simple - but is there something like that in the standard library? I'm using Visual Studio 2008, by the way, and I don't want to attach a 3rd party framework like Boost or something.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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




回答6:


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.




回答7:


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).




回答8:


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>;


来源:https://stackoverflow.com/questions/2433240/what-wrapper-class-in-c-should-i-use-for-automated-resource-management

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