我创建了一个模板,该模板可以保存指向任何种类资产的指针及其ID,称为ResourceHolder,但是当我使用该模板实例中指向纹理的指针来加载纹理以进行精灵化时,它是白色正方形。这是我在ResourceHolder.hpp中的代码:
#ifndef RESOURCEEHOLDER_H
#define RESOURCEHOLDER_H
#include "TexturesId.h"
#include "assert.h"
#include <SFML/Graphics.hpp>
#include <stdexcept>
#include <memory>
#include <string>
#include <map>
using namespace sf;
template<typename Resource,typename Identifier>
class ResourceHolder
{
public:
void load(Identifier id,const std::string &filename);
Resource& get(Identifier id);
const Resource& get(Identifier id) const;
protected:
private:
std::map<Identifier,std::unique_ptr<Resource>> mResourceMap;
};
#endif // TEXTUREHOLDER_H
然后在ResourceHolder.cpp中的代码
#include "ResourceHolder.h"
using namespace sf;
template<typename Resource,typename Identifier>
void ResourceHolder<Resource,Identifier>::load(Identifier id,const std::string& filename)
{
std::unique_ptr<Resource> resource(new Resource());
if(!(resource->loadFromFile(filename)))
{
throw std::runtime_error("TextureHolder failed to load " + filename);
}
auto inserted=mResourceMap.insert(std::make_pair(id,std::move(resource)));
assert(inserted.second);
}
template<typename Resource,typename Identifier>
Resource& ResourceHolder<Resource,Identifier>::get(Identifier id)
{
auto found=mResourceMap.find(id);
assert(found!=mResourceMap.end());
return *found->second;
}
template<typename Resource,typename Identifier>
const Resource& ResourceHolder<Resource,Identifier>::get(Identifier id) const
{
auto found=mResourceMap.find(id);
assert(found!=mResourceMap.end());
return *found->second;
}
template class ResourceHolder<Texture,Textures::ID>;
TextureId.h:
#ifndef TEXTURESID_H_INCLUDED
#define TEXTURESID_H_INCLUDED
namespace Textures
{
enum ID{Landsape,Airplane,Missile};
}
#endif // TEXTURESID_H_INCLUDED
最后是Game.cpp
Game::Game(int x,int y,std::string &Name)
:window(VideoMode(x,y),Name),texture(),
mPlayer()
{
ResourceHolder<Texture,Textures::ID> th;
th.load(Textures::ID::Airplane,"plane.png");
Texture texture=th.get(Textures::ID::Airplane);
mPlayer.setTexture(texture);
mPlayer.setPosition(window.getSize().x/2,window.getSize().y/2);
}
有问题的代码是Game.cpp中的代码
Game::Game(int x,int y,std::string &Name)
:window(VideoMode(x,y),Name),texture(),
mPlayer()
{
ResourceHolder<Texture,Textures::ID> th;
th.load(Textures::ID::Airplane,"plane.png");
Texture texture=th.get(Textures::ID::Airplane);
mPlayer.setTexture(texture);
mPlayer.setPosition(window.getSize().x/2,window.getSize().y/2);
}
ResourceHolder
以及Texture
仅存在于Game
构造函数的本地范围内。一旦构造函数执行完毕,rh
和texture
都将超出范围,并且Sprite对纹理的引用将无效,从而导致white square problem。