gpt4 book ai didi

c++ - 从非托管 C++ 显式调用托管析构函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:50:57 24 4
gpt4 key购买 nike

我有一个 native C++ 项目,它通过包装类使用 .NET 图表实用程序。包装类的简化版本是这样的;

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
}

函数将通过包装器负责实例化、操作和删除图表;

void CreateChart()
{
ChartWrapper* chart = new ChartWrapper();
// Do stuff to the chart
delete chart;
}

有可能在程序实例期间创建数百个图表。当我完成每个包装器时,我通过调用 delete 显式删除它,但是托管对象 ManagedChartClass 仅在程序退出时才被破坏。这会导致建立不需要的内存,并且出现“内存不足”异常。

如何确保在销毁包装器时销毁托管对象?

最佳答案

您可以使用 auto_gcroot<T> , 而不是 gcroot<T> .不同之处在于 auto_gcroot<T>destructor “还会破坏拥有的对象。”

在托管世界中,这会映射到调用 IDisposable.Dispose()在包装的托管类型上,前提是它实现了 IDisposable .

关于c++ - 从非托管 C++ 显式调用托管析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com