Ryan
Ryan

Reputation: 567

Garbage Collection in C++/CLI

Consider the below:

#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;
}

My output is simply: TestClass()

I never get ~TestClass(). This is a simplification of an issue I am having in production code, where a list of handles is being cleared and repopulated multiple times, and the handle destructors are never being called.

What am I doing wrong?

Sincerely, Ryan

Upvotes: 3

Views: 4402

Answers (1)

James Hopkin
James Hopkin

Reputation: 13973

~TestClass()

declares a Dispose function.

!TestClass()

would declare a finaliser (the equivalent of C#'s ~TestClass) which gets called on a gc collection (although that's not guaranteed).

Upvotes: 4

Related Questions