So I started reading the sfml development book to look at the possible structure of a game and to gain some more knowledge of the sfml library. There are some points in the book that I don't understand WHY they chose to implement something in a particular way. An example is the resource class in the beginning of the book. When I looked at it something struck me as weird but I didn't realize what it was until a fellow stack overflow member reminded me that the [] operator of the std::map container creates an object if the key doesn't exist.
The book's implementation:
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("ResourceHolder::load - Failed to load " + filename);
}
auto inserted = mResourceMap.insert(std::make_pair(id, std::move(resource)));
assert(inserted.second);
}
Another possible implementation:
template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& filename)
{
assert(mResourceMap.find(id) == mResourceMap.end());
if (!mResourceMap[id].loadFromFile(file))
{
mResourceMap.erase(id);
throw std::runtime_error("ResourceHolder::load - Failed to load " + file);
}
}
Are there any advantages in the book's implementation?
EDIT: Just noticed that this is the help section's general category.