简体   繁体   中英

How can I delete an object from a pointer to a pointer array?

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.

Its best not to use the raw pointers at all and go for stl containers. One possible way could be as below.

using InputPtr = std::unique_ptr<Input>;
std::vector<InputPtr> Inputs;
Inputs.emplace_back(std::make_unique<DigitalInput>());

No need to worry about memory leaks any more. The other option you have is to use std::shared_ptr depending upon how you intend to use your InputList;

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...)

If you want to delete objects in the heap:

for(int i = 0; i < totalInputs; ++i) delete Inputs[i]; delete[] Inputs for(int i = 0; i < totalInputs; ++i) delete Inputs[i]; delete[] Inputs ;

Edit: If you're using a microcontroller it would be best to allocate at the stack instead.

Define a maximum size on your array. Like:

const int MAX = 5;
Inputs inputs[MAX][MAX];

then just asign objects to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM