Hi folks,
what's the best way to reserve some space in the stack for a uninitialised object. For example:
1 2 3 4 5 6 7 8 9 10 11 12
uint8_t* data = m_prefix;
MyUnitialisedObject _object; // MyUnitialisedObject is a template param without default ctor
while(...){
... a pile of code here ...
if(condition){
_object = MyUnitialisedObject::init(...)
data = _object.data()
}
... use data here ...
}
The whole purpose of _object is to keep the space pointed by the variable `data' alive when the condition arises.
p.s. the preview button for posts is broken in my browser, same for you?
uint8_t _object_space[sizeof(MyUnitialisedObject)];
MyUnitialisedObject _object = *reinterpret_cast<MyUnitialisedObject*>(_object_space); // reserve space in the stack
which is, admittedly, ugly as a yellow renault 4. I am hoping for something better from you!
it doesn't matter if it copies garbage, the whole point is that the scope of the variable _object remains visible as long as the variable `data'. To understand the issue, suppose that MyUnitialisedObject was something like:
This will reserve sizeof(MyUnitialisedObject) bytes on the stack (assuming that sizeof(uint8_t) is 1) with _object_space as a uint8_t pointer. This memory reference is only valid as long as _object_space is within scope.
Why not just (not tried):
static MyUnitialisedObject _object[1];
_object is now a pointer to memory space of size sizeof(MyUnitialisedObject) that doesn't become invalid when _object goes out of scope. But this will be space on the heap rather than the stack.
Hye seeplus, that's correct. The point is that _object_space is visible as long as the variable `data' is.
static MyUnitialisedObject _object[1]; won't work because MyUnitialisedObject does not have a default/empty ctor.Indeed, I don't know what it is its constructor, it's a template arg.