This question is targeted to embedded systems!
I have the following options to initialize an object:
Object* o = new Object(arg);
This puts the object in the heap and returns a pointer to it. I prefer not to use dynamic allocation in embedded software.
Object o = Object(arg);
This creates a new object in the stack and then copies it to object o
and removes it after. This can cause stack overflow if the object is big enough to fit in RAM but not in the stack. I have seen this happening with optimization turned off, I haven't explored if it's different with optimization enabled.
Object o(arg);
This creates the object without making a copy, however how can I "initialize" o
again?
For embedded I prefer the last option since the heap is not used and there's no temporary object in the stack that can do a stack overflow.
However I am puzzled on how I can reinitialize the object again since:
o.Object(arg)
is not allowed.
I could create a method called init(arg) and call
o.init(arg)
that does the same initialization as Object::Object(arg)
but I would prefer not to have to create an extra method with a "non-standard" name I need to remember.
Is there a way to call the constructor of an already created object to reinitialize it again without making a copy?