2010-06-29 69 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引用也會更新爲指向其新位置。