DGtal
DGtal copied to clipboard
Missing virtual destructor in base class `CubicalComplex` with public inheritance
VoxelComplex
publicly inheritates from CombicalComplex
but the later class is not designed for this: its destructor should be virtual
so that to guarantee that a VoxelComplex
object is correctly destroyed in all cases. In particular, in case of polymorphism, the destructor of the attributes of VoxelComplex
will not be called thus leading to potential memory leak (attributes are CountedPtrOrPtr
).
Simple example:
#include <iostream>
struct CountedPtrOrPtr
{
CountedPtrOrPtr() { std::cout << "CountedPtrOrPtr" << std::endl; }
~CountedPtrOrPtr() { std::cout << "~CountedPtrOrPtr" << std::endl; }
};
struct CubicalComplex
{
CubicalComplex() { std::cout << "CubicalComplex" << std::endl; }
~CubicalComplex() { std::cout << "~CubicalComplex" << std::endl; }
};
struct VoxelComplex : CubicalComplex
{
CountedPtrOrPtr ptr;
VoxelComplex() { std::cout << "VoxelComplex" << std::endl; }
~VoxelComplex() { std::cout << "~VoxelComplex" << std::endl; }
};
int main()
{
CubicalComplex* cc = new VoxelComplex();
delete cc;
return 0;
}
that outputs:
CubicalComplex
CountedPtrOrPtr
VoxelComplex
~CubicalComplex
but with a virtual
CubicalComplex
destuctor:
CubicalComplex
CountedPtrOrPtr
VoxelComplex
~VoxelComplex
~CountedPtrOrPtr
~CubicalComplex