考虑以下:
#include <iostream>
public ref class TestClass {
public:
TestClass() { std::cerr << "TestClass()\n"; }
~TestClass() { std::cerr << "~TestClass()\n"; }
};
public ref class TestContainer {
public:
TestContainer() : m_handle(gcnew TestClass) { }
private:
TestClass^ m_handle;
};
void createContainer() {
TestContainer^ tc = gcnew TestContainer();
// object leaves scope and should be marked for GC(?)
}
int main() {
createContainer();
// Manually collect.
System::GC::Collect();
System::GC::WaitForPendingFinalizers();
// ... do other stuff
return 0;
}
我的输出很简单: 测试类()
我从来没有得到 ~TestClass()。这是我在生产代码中遇到的一个问题的简化,其中句柄列表被多次清除和重新填充,句柄析构函数从未被调用。
我做错了什么?
真诚的, 瑞安
最佳答案
~TestClass()
声明一个 Dispose 函数。
!TestClass()
将声明一个终结器(相当于 C# 的 ~TestClass
),它在 gc 集合上被调用(尽管不能保证)。
关于.net - C++/CLI 中的垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/830119/