When wrapping C-like APIs that use pointers on undefined structures, I generally go to std::unique_ptr
with a custom deleter to handle resources.
Occasionally, the C API will attribute integer IDs rather than pointers to the resources. I was wondering what would be the best practice to handle those. Should I rewrite a class similar to std::unique_ptr
just for the sake of handling IDs than pointers? Should I dynamically allocate memory for those IDs to get a pointer I can pass to std::unique_ptr
? Should I reinterpret the ID as a pointer? Or is there (hopefully) a better solution yet?
While you could (ab)use std::unique_ptr for this, it seems clearer and very simple to write your own template class. You can decide whether the deleter is part of the type (as in unique_ptr) or a constructor argument (as in shared_ptr). You may also want some bespoke classes where there are meaningful operations to be performed directly on the handle (copying, indexing into it, etc).