I'm working on an embedded system, where memory is scarce, and more importantly, since there's a soft realtime constraint (i.e. it's a bug if we don't make the deadline, but no one dies), I cannot use dynamic memory allocation.
However, there's the occasional need to re-initialize a subsystem, and there's been a number of bugs related to not-quite-everything getting either cleaned up or reset correctly. This is of course exactly the problem that constructors and destructors are supposed to solve, but since we don't allocate dynamically, we can't use the idiom where we'd destruct the object and then allocate a new one from scratch (mostly the objects of relevance here are globals).
So in the end there's usually setup code in a constructor, and a reinitialize -type function, which resemble each other but are not identical, since the reinitialize function also does a lot of what a destructor would do.
One way out that I'm thinking of is to write a "renew" -template (this is just a draft, may contain erors and possibly not complet):
template<typename T, typename .. Args>
void renew(T & obj, Args&&... args) {
obj.~T();
new(&obj) T(std::forward<Args>(args)...);
}
which could be used to reinitialize non-dynamically alloctated variables. So for example
A a{17};
... //Do something with a
renew(a, 14);
...//work with the new a, no need to reallocate memory
This would allow getting some of the advantages of constructors and destructors (primarily single way to initialize and deinitialize an object) without dynamic memory allocation. Note that the usage above is simplified, in practice this would mostly be used in very specific points in the main loop and on global objects representing the actual physical subsystems.
Question: is this a sensible way of going about it? Or is there a better alternative?
There's a very similar question here Calling a constructor to re-initialize object. I'm asking much the same thing but specifically in context of embedded programming, where I can't do things the usual way with dynamic allocation.