This question is based on https://arduino.stackexchange.com/questions/81857/what-would-be-the-best-way-of-dynamically-change-instances-regarding-dynamic-m
I have a base class, and (possibly) many derived classes from it. I want to have 4 instances to those derived classes, but those instances change. E.g. assume derived classes C1..C20, then one instance to C4 is deleted, and a new instance C7 is created.
Due to memory limitations, I cannot create 4 instances of all derived class.
I work on an Arduino platform. Can I assume:
delete
an instance and new
an instance, and the derived classes do not have any instance variables, the memory gap by delete
the first instance, will be filled with the instance created by new
? Note that the derived classes have different methods (but I think this only affects the V-table).In case 2 is true, what would be the best way to keep both instances the same (memory) size? Like placing an unused byte array for the difference, e.g.:
class C
{
byte a;
}
class C1: C
{
byte a;
long b;
}
class C2: C
{
byte a;
byte _unused[4];
}
Guess I also have to keep alignment into account?
You have to make sure that
Then you can allocate memory enough to hold 4 instances and use new(buffer) Type
to construct the instances. Once you're done and want to switch the types, you call the destructor on each instance and use placement new for some other type.