I have a native C++ project that makes use of .NET charting utilities through a wrapper class. A cut-down version of the wrapper class is something like this;
class ChartWrapper
{
private:
gcroot<ChartNamespace::ManagedChartClass^>* m_Chart;
public:
ChartWrapper(): m_Chart(new gcroot<ChartNamespace::ManagedChartClass^>)
{
*m_Chart = gcnew ChartNamespace::ManagedChartClass;
}
~ChartWrapper()
{
delete m_Chart;
}
// Methods to interact with the chart
}
A function will take care of instantiating, manipulating, and deleting the chart through the wrapper;
void CreateChart()
{
ChartWrapper* chart = new ChartWrapper();
// Do stuff to the chart
delete chart;
}
There is the potential of creating hundreds of charts during the program instance. I explicitly delete each wrapper by calling delete
when I am done with it, but the managed object ManagedChartClass
is only destructed when the program exits. This causes memory to build up that is not needed and I get 'out of memory' exceptions.
How can I ensure that the managed objects are destructed when the wrapper is destructed?
You can use auto_gcroot<T>
, instead of gcroot<T>
. The difference is that auto_gcroot<T>
's destructor "also destructs the owned object."
In the managed world, this maps through to calling IDisposable.Dispose()
on the wrapped managed type, provided it implements IDisposable
.