2014-05-12 71 views
2

我試圖在D中使用Derelict3構建一個簡單的3D遊戲引擎。事情一直在順利進行,直到我開始使用關聯數組繪製opengl glGenTextures/glGenBuffers。爲此,我構建了一個簡單的結構,其中包含對要綁定的紋理/ vbo以及從opengl返回的id的引用。然後這將被映射爲紋理/ vbo的散列以供稍後檢索。關聯數組不存儲映射

但是,只要它完成設置實際映射,映射就會被神奇地移除。我還不明白爲什麼。下面是我想要實現的一個簡單示例,並且可以觀察到相同的行爲。

module main; 

import std.datetime; 
import std.stdio; 

class Placeholder { 
    string value; 

    this(string value) { 
     this.value = value; 
    } 
} 

private class ResourceInfo { 
    uint id; 
    uint time; 
    Object resource; 

    static ResourceInfo getOrCreate(Object resource, ResourceInfo[uint] map) { 
     uint hash = resource.toHash(); 
     ResourceInfo* temp = (hash in map); 
     ResourceInfo info; 
     if (!temp){ 
      info = new ResourceInfo(); 
      info.resource = resource; 
      map[hash] = info; 
     } else{ 
      info = *temp; 
     } 
     // placeholders.lenght is now 1 (!) 
     info.time = stdTimeToUnixTime(Clock.currStdTime); 
     return info; 
    } 
} 

protected ResourceInfo[uint] placeholders; 

void main() { 

    Placeholder value = new Placeholder("test"); 

    while(true) { 
     ResourceInfo info = ResourceInfo.getOrCreate(value, placeholders); 
     // placeholders.lenght is now 0 (!) 
     if (!info.id) { 
      info.id = 1; // Here we call glGenBuffers(1, &info.id); in the  engine 
     } else { 
      // This never runs 
      writeln("FOUND: ", info.id); 
     } 
    } 
} 

調用placeholders[value.toHash()] = info手動時,沒有ID存在暫時修復,但後來我開始越來越在_aaApply2object.Error: Access Violation_d_delclass每當我嘗試了幾秒鐘後訪問的info一個實例。

任何人都看到任何明顯的我失蹤?

+0

難道說那些被分配的malloc()或通過從d使用一些C/C++庫相似?通常GC對它們一無所知,只要你知道,它們就可以是免費的()d ... – DejanLekic

+0

我不喜歡你如何刪除一個對象的類型信息,當然,你可以投射它並檢查它的零,但我這樣做的方式是隱藏投射和檢查模板的方法,應該返回類型,如果演員失敗我會斷言假/拋出,取決於你的風格。這樣你就不會有凌亂的鑄造代碼直接在你的使用代碼 – Quonux

回答

3

最好我可以猜想是未初始化關聯數組的通常僞行爲。意思是按值傳遞它們,然後向它們添加鍵,但只有只有如果該數組已被初始化。這是目前實施中的邊緣情況。嘗試使用ref但是,它應該解決的事情:

static ResourceInfo getOrCreate(Object resource, ref ResourceInfo[uint] map) 
+0

ref做到了! – Freddroid