I have a piece of low-level code with callbacks: Init and Cleanup, and others. I don't control the arguments of the callbacks. I chose to use a global variable for managing the state, say class state.
Here's a simple construct I can use:
std::unique_ptr<state> s;
void Init() {
s = make_unique<state>();
}
void Cleanup() {
s.reset();
}
It's simple and self explanatory. The main drawback: it uses the heap, which means that performance is sacrificed, and the allocation can fail.
Alternatively, I can use a construct similar to the following:
alignas(state) unsigned char s_buf[sizeof(state)];
void Init() {
state* s = new(s_buf) state;
}
void Cleanup() {
state* s = reinterpret_cast<state*>(s_buf);
s->~T();
}
Now I don't use the heap, but it's much uglier and more error prone, and I'm not even sure whether there's an undefined behavior lurking somewhere. I might be able to encapsulate it in a wrapper class, but there's so much that can go wrong.
Is there any common construct to achieve what I'm trying to do, i.e. having a unique_ptr-like class without the heap allocation?