全局访问单例数据



所以我正在制作一个图形应用程序(游戏),我想使用资源管理器。对于这门课,我决定使用单例设计。所以在我的主方面.cpp我会加载类似的东西......

ASSET_MANAGER.LoadImage("res/graphics/background.png", "background");

这是上面行中使用的宏/方法的含义。这是一种代码的混搭,我必须使事情看起来更简单,而不是将几百行代码粘贴到这里。

资产管理者.h

#define ASSET_MANAGER AssetManager::GetAssetManager()
#define DEBUG
class AssetManager {
public:
static AssetManager &GetAssetManager();
//-----------------------------------------------------------------------------
// Purpose: Load a new image for the game to use. This function will store an
//          instance of the asset in memory (in a hash map corresponding with
//          the data type provided.
//
// param file: The location on disk of the asset
// param key: The string you use to receive this asset (defaults to the path str)
//-----------------------------------------------------------------------------
bool LoadImage(const char *file, const char *key = "");
//-----------------------------------------------------------------------------
// Purpose: Returns the image
//
// param key: The string used to store the asset in memory
//-----------------------------------------------------------------------------
ALLEGRO_BITMAP *GetImage(const char *key);
//-----------------------------------------------------------------------------
// Purpose: Destroys an asset that is presumably no longer needed by the game.
//          This function is good for performance so that you don't use more
//          RAM than you need to.
//
// param key: The string you use to receive this asset (defaults to the path str)
//-----------------------------------------------------------------------------
void DiscardImage(const char *key);
private:
    AssetManager();
    ~AssetManager();
    std::map<const char *, std::shared_ptr<ALLEGRO_BITMAP>> _ImageMap;
}

资产管理.cpp

AssetManager &AssetManager::GetAssetManager() {
    static AssetManager instance;
    return instance;
}
bool AssetManager::LoadImage(const char *file, const char *key) {
    key = key == "" ? file : key;
    std::shared_ptr<ALLEGRO_BITMAP> x(al_load_bitmap(file), al_destroy_bitmap);
    if (!x) {
        fprintf(stderr, "Failed to load %sn", file);
        return false;
    }
#ifdef DEBUG
    printf("DEBUG: Loaded %sn", key); //debug
#endif // DEBUG
    _ImageMap.insert(std::pair<const char *, std::shared_ptr<ALLEGRO_BITMAP>>(key, x));
    return true;
}
ALLEGRO_BITMAP *AssetManager::GetImage(const char *key) {
    return _ImageMap.find(key) != _ImageMap.end() ? _ImageMap.at(key).get() : nullptr;
}
void AssetManager::DiscardImage(const char *key) {
    _ImageMap.erase(key);
#ifdef DEBUG
    printf("DEBUG: Discarded %sn", key); //debug
#endif // DEBUG
}

这个类只适用于我初始化资源管理器的类,而我希望它可以在我称之为ASSET_MANAGER的任何地方工作。它编译得很好,只有当我尝试在不同的类中使用管理器并将其传递给 allegro 函数时,它才会崩溃,因为它返回的是空而不是正确的 allegro 数据类型。我对此有什么不明白的?

地图中的 Char* 存储位置而不是使程序认为它为空的数据。

最新更新