unique_ptr | Unique for autoclose handle
Vitaliy Fadeev
vital.fadeev at gmail.com
Thu Dec 15 06:08:32 UTC 2022
On Wednesday, 14 December 2022 at 17:44:05 UTC, Ali Çehreli wrote:
> On 12/14/22 09:41, Ali Çehreli wrote:
>
> > // According to documentation, the handler must be
> created dynamically:
> > // We make a unique owner for it:
>
Last try is customized **std.typecons.Unique**:
```
module safehandle;
import core.sys.windows.windows;
import std.typecons;
struct Unique( T, alias DTOR )
{
...
~this()
{
if (_p !is null)
{
DTOR( _p );
destroy(_p);
_p = null;
}
}
...
}
alias SafeHandle = Unique!(void,CloseHandle);
```
and using :
```
SafeHandle open_keyboard_device2( ... )
{
...
SafeHandle dev_handle =
CreateFileW( ... );
...
return dev_handle;
}
```
```
void main()
{
...
auto dev = open_keyboard_device2( ... );
process_device( dev );
...
// auto-close handle
}
```
Open source is good!
Thanks all!
and in future:
```
alias SafeHandle = Unique!(void,CloseHandle)
alias Safe_SDL_Window = Unique!(SDL_Window,SDL_DestroyWindow)
alias Safe_SDL_Surface = Unique!(SDL_Surface,SDL_FreeSurface)
alias Safe_SDL_Texture = Unique!(SDL_Texture,SDL_DestroyTexture)
alias Safe_SDL_Renderer =
Unique!(SDL_Renderer,SDL_DestroyRenderer)
```
Code is good, but testing....
More information about the Digitalmars-d-learn
mailing list