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

前端 未结 8 1057
余生分开走
余生分开走 2020-12-16 13:56

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 clas

相关标签:
8条回答
  • 2020-12-16 14:40

    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.

    0 讨论(0)
  • 2020-12-16 14:40

    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.

    0 讨论(0)
提交回复
热议问题