I'm still new to manual destruction in C++ (came from languages with garbage collection). I have the following in one of my classes:
Input** Inputs;
Which gets initialized as follows:
this->Inputs = new Input* [totalInputs];
And can get reassigned to later on in my code depending on user input, similar to this:
this->Inputs[inputNumber] = new DigitalInput(params...)
The problem with this is that it's open to memory leaks when reassigning the object at that location due to releasing the old object.
What is the best way to delete the old object once it's been reassigned?
Edit: I forgot to include that this is on an AVR microcontroller which is running on the Arduino codebase.
Edit 2: The reason that I'm doing this this way is because the user is allowed to send commands to the unit which will change the input type (ie: send a command and this->Inputs[inputNumber] = new AnalogInput(params...)
. Also the reason it's a pointer to an array of pointers is because the constructor for this object will generate that array based on the totalInputs
argument passed in. This is in a shared library which is used on a few different units.
If you're reassigning a member of the array to point to a new object, you can first deallocate the old object, if any.
Input* oldInput = this->Inputs[inputNumber];
delete oldInput;
this->Inputs[inputNumber] = new DigitalInput(params...)