Description
Hi there,
first of all thanks a lot for your great work and effort! (thumbsup)
I just stumbed accross an issue with the Stream class, when writing a destructor for a derived class. Specifically, the class has a variable pSerial
of type Stream*
, which is allocated via
this->pSerial = (SoftwareSerial*) (new SoftwareSerial(this->pinRx, this->pinTx, this->inverseLogic));
But when I try to delete it inside the class constructor via
delete (SoftwareSerial*) this->pSerial;
or delete static_cast<SoftwareSerial*>(this->pSerial);
I get the warning
warning: deleting object of polymorphic class type 'SoftwareSerial' which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor]
If I understand it correctly, the issue is that class Stream
does not have a virtual destructor - or any destructor for that matter, see here.
I understand that using SoftwareSerial
dynamically is uncommon, but I have no control over the "correct" use of my library. Therefore I want to avoid memory leaks by releasing the instance again.
To avoid this issue I propose to add a dummy virtual destructor to class Stream
. Alternatively, do you know how I could avoid this issue? I tried calling the destructor explicitly
((SoftwareSerial*) this->pSerial)->~SoftwareSerial();
which does compile without warning. However, Co-Pilot advises against it, as it doesn't seem to release allocated memory. Any other ideas?