C ++:使方法每次返回相同的对象 [英] C++: Making method return the same object every time

查看:136
本文介绍了C ++:使方法每次返回相同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个函数加载一个文件(在这种情况下是一个OpenGL纹理),但实际上只加载文件一次,每次调用后,它只是返回它最初加载的东西。

I would like to have a function that loads a file (in this case an OpenGL texture), but only actually loads the file once, and every time it is called after that it just returns what it initially loaded.

这是一个很好的方法吗?

What would be a good way to do this?

谢谢。

推荐答案

您需要一些地方来存储该状态。这可以在一个对象内或作为一个静态变量。让我们说:

You need some place to store that state. That can be either inside an object or as a static variable. Let's say:

class TextureLoader {
public:
    TextureLoader() {}
    GLuint loadTexture(std::string const & filename){
        std::map<std::string, GLuint>::iterator it = m_loadedTextures.find(filename);
        if(it == m_loadedTextures.end()){
            GLuint id = load(filename);
            m_loadedTextures[filename] = id;
            return id;
        }
        else{
            return it->second;
        }
    }
    ~TextureLoader(){
        // iterate and delete textures
    }
private:
    GLuint load(std::string const & filename){
        // real loading
    }
    std::map<std::string, GLuint> m_loadedTextures;
};

这篇关于C ++:使方法每次返回相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆