2010-06-29 68 views
0

嗨,不幸的是我在整个垃圾收集事情上并不那么优秀。现在我不能确定,如果我要惹上麻烦,如果我做了以下内容:多个gcrooted托管对象之间的C++/CLI交换对象引用

// unmanaged Class 
class CUnmagedClass : public CCmdTarget 
{ 
    auto_gcroot<Dictionary<int, System::String^>^> m_dict; 
    auto_gcroot<SomeManagedClass^> m_managedClass; 

    // create first manage object in one gcroot 
    CUnmagedClass() 
    :dict(gcnew Dictionary<LANGID, System::String^>()) 
    {} 

    // do something with the dictionary 
    void AddData(int key, String^ value) 
    { 
     this->m_dict->Add(key, value); 
    } 

    // Method that could be called multiple times 
    void DoOtherThings(Data^ data) 
    { 
     // create a new object on every method call 
     // old object can be garbage collected 
     this->m_managedClass = gcnew SomeManagedClass(data); 
     // assign a reference to the dictionary from the other gcroot 
     this->m_managedClass->DictProp = this->m_dict; 

     this->m_managedClass->DoSomething(); 
    } 

} 

所以我的问题是,如果我重写this->m_managedClass和值SomeManagedClass实例是垃圾回收旧。系统是否尝试收集this->m_managedClass->DictProp中的对象,因为它不再与第二个gcroot连接,或者垃圾收集器足够聪明以知道在其他gcroot中有剩余的引用?

回答

1

系统也不会尝试收集this->m_managedClass->DictProp,因为它足够聪明可以知道该对象被其他gcroot引用。

gcroot这个聪明的原因是它包装System::Runtime::InteropServices::GCHandle,这是垃圾回收堆的句柄。 GCHandle类允许您的非托管对象存储有效的托管引用。另外,即使您的托管对象被垃圾收集器移动,GCHandle引用也会更新为指向其新位置。