关联数组不存储映射

时间:2014-05-12 17:52:58

标签: arrays opengl d associative-array

我正在尝试使用Derelict3在D中构建一个简单的3D游戏引擎。事情进展顺利,直到我开始使用关联数组来映射opengl glGenTextures / glGenBuffers 。为此,我构造了一个简单的结构,其中包含对要绑定的texture / vbo的引用以及从opengl返回的id。然后将其与texture / 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);
        }
    }
}

当没有 id 时,手动调用placeholders[value.toHash()] = info会暂时修复它,但每当我尝试使用object.Error: Access Violation_aaApply2时,我就会开始_d_delclass几秒钟后访问info的实例。

有人看到任何明显我失踪的事吗?

1 个答案:

答案 0 :(得分:3)

最好我能猜测是未初始化的关联数组的常见伪行为。通过值传递它们然后向它们添加键的含义有效,但如果该数组已经初始化。它是实现中的当前边缘情况。尝试使用ref,但它应该解决问题:

static ResourceInfo getOrCreate(Object resource, ref ResourceInfo[uint] map)
相关问题