C++ Logo


Advanced search

Improving the usability/efficiency of unique_resource

From: Jim Porter <jporterbugs_at_[hidden]>
Date: Thu, 5 Aug 2021 18:25:58 -0700
LFTS3's[1] `unique_resource` is a welcome improvement over writing one's
own RAII wrappers for resources (or worse, manually acquiring/releasing
them). However, in using it, I've found a couple of weaknesses.

First, unlike `std::unique_ptr`, `unique_resource` doesn't have
`operator bool` to check if it's currently holding a resource.
`unique_resource` is meant to be used in similar situations as
`std::unique_ptr`, so the same reasons for needing to check this apply
here. (Since `unique_resource` already keeps track of whether it's
holding a valid resource handle to know when to release it, the
implementation is trivial.)

Second, `unique_resource` currently holds both the resource handle and a
boolean flag to track when a resource is held. For many handle types,
this isn't necessary, since the handle has a statically-defined
"invalid" value. This can be an issue when you have many
`unique_resource`s, e.g. when working with OpenGL objects[2]. For
handles like this, `unique_resource` could accept a template parameter
specifying the invalid value. It may also be useful to keep the current
behavior where *any* value is valid, although I'm not aware of a
real-world handle type that would require this. Statically specifying
the invalid value for a handle should also remove the need for
`make_unique_resource_checked`. (Of course, the implementation of
`operator bool` would be trivial in this case as well.)

One area this *doesn't* address is when a handle type has a range of
invalid values, e.g. all values < 0. However, I'm not sure this is a
common enough case that the standard should account for it.

If the above sounds reasonable, I can work on a proposal, assuming
others are willing to provide some guidance on the processes.

- Jim

[1] https://wg21.link/p0052r10
[2] Represented by a `GLuint` handle where 0 is invalid

Received on 2021-08-05 20:26:10