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

标签 .net c++ memory-management garbage-collection

考虑以下:

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

相关文章:

C# .net 使复选框充当单选按钮

c++ - 在 Eclipse CDT 中使用运算符 [] 的 vector vector 中未解析 "size"

java - 追加到数组与写入文件

ios - 为什么我应该在这种情况下使用自动释放?

c - 为什么我的程序有内存泄漏检查错误?

.net - MS Access数据库的自动压缩和修复

c# - 字符串内容相同但长度不同

c# - 如何在 C# 中连接到 OAuth?

c++ - 根据可调用的签名自动选择一元与二进制 std::transform 函数重载

c++ - 嵌套命名空间中的流运算符重载