【发布时间】:2014-06-02 20:59:50
【问题描述】:
我正在尝试为我的游戏创建一个资源类(它使用 SFML API)。 基本上,我首先加载所需的资源,然后在需要时获取对它们的引用,以避免资源类的繁重构造。
(我以 sf::Texture 类为例)
问题在于加载函数。 为了制作 sf::Texture 我必须使用默认构造函数,然后使用它的 loadFromFile 函数来获取所需的纹理。假设我有一张包含文件名对和相应资源的地图:
std::map<std::string, sf::Texture> textures;
sf::Texture texture;
texture.loadFromFile(file);
现在如果我这样做:
textures.emplace(file, texture);
这将使用复制构造函数来制作另一个 sf::Texture。 所以我想我应该使用 std::move 但显然 sf::Texture 类没有移动构造函数,所以它仍然会复制。为了解决这个问题,我现在使用一个包含文件名对和对象的各自唯一指针的映射。 所以我这样做:
std::unique_ptr<sf::Texture> texture(new sf::Texture);
texture->loadFromFile(file);
textures.emplace(file, std::move(texture));
完整的函数如下所示:
void ResourceManager::loadTexture(std::string file)
{
std::unique_ptr<sf::Texture> texture(new sf::Texture);
if (!texture->loadFromFile(file))
{
throw std::runtime_error("ResourceManager::load - Failed to load " + file);
}
auto inserted = mtextures.emplace(file, std::move(texture));
assert(inserted.second);
}
不过,我在移动语义方面没有太多经验,我不确定我是否做对了一切。基本上,我错过了什么吗?如果这个问题不属于堆栈溢出,我很乐意将其移至适当的站点。
【问题讨论】:
-
apparently the sf::Texture class doesn't have a move constructor。事实上,SFML 2 是用 C++98 编写的。
标签: c++ c++11 resources sfml move-semantics