gpt4 book ai didi

.net - C++/CLI 中的垃圾收集

转载 作者:搜寻专家 更新时间:2023-10-31 00:49:44 25 4
gpt4 key购买 nike

考虑以下:

#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/

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