c++ - Is relying on the type of a Windows handle being a pointer ok? -
windows handles annoying remember clean after (doing gdi created pens , brushes great example). raii solution great, great making 1 full (rule of five) raii class each different type of handle? of course not! best can see 1 full generic raii class other classes defining when handle should cleaned up, other handle-specific aspects.
for example, simple module class defined (just example):
struct module { module() : handle_{nullptr} {} module(hmodule hm) : handle_{hm, [](hmodule h){freelibrary(h);}} {} operator hmodule() const {return handle_.get();} private: handle<hmodule> handle_; };
that's fine , dandy, , no destructor or needed. of course, though, being able write handle
class not need destructor or nice, too. why not use existing raii techniques? 1 idea use smart pointer void
, won't work. here's how handles declared under normal circumstances:
#define declare_handle(n) typedef struct n##__{int i;}*n declare_handle(haccel); declare_handle(hbitmap); declare_handle(hbrush); ...
it differentiates between handle types, good, makes using smart pointer void
impossible. if, instead, since handles are, definitions, pointers, type extracted?
my question whether following safe assumption make. uses handle desktop, must closed. barring differences between shared , unique pointers (e.g., freelibrary
has own reference counting semantics), assuming handle pointer , making smart pointer whatever it's pointing okay, or should not use smart pointers , make handle
implement raii aspects itself?
#include <memory> #include <type_traits> #include <utility> #include <windows.h> int main() { using underlying_type = std::common_type<decltype(*std::declval<hdesk>())>::type; std::shared_ptr<underlying_type> ptr{nullptr, [](hdesk desk){closedesktop(desk);}}; }
i believe windows pointers technically pointers internal objects inside windows kernel part of system (or sometimes, possibly, user-side objects allocated kernel code, or variation on theme).
i'm far convinced should treat them pointers tho'. pointers in purely technical perspective. no more "pointers" c style "file *" pointer. don't think suggest use of shared_ptr<file*>
deal closing files later on.
wrapping handle cleans later means idea, don't think using smart pointer solutions right solution. using templated system knows how close handle ideal.
i suppose need deal "i want pass handle here somewhere else" in way works involved - e.g. have function fetches resources in way, , returns handles resources - return wrapped object, , if so, how copy work?
what if need save copy of handle before using 1 (e.g. save current pen, set custom one, restore)?
Comments
Post a Comment