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.
What I mean is that when doing:
std::unique_ptr<Resource> resource(new Resource());
We make a new Resource object using the default constructor and we set the pointer to it.
We then move construct an std::pair and insert it to the map.
When we have a map:
std::map<std::string, Resource> resources
and we call,
resources[id]
if id does not exist it simply probably makes a node for the std::pair using it's appropriate constructor. I am not sure how they have implemented the RBT but I don't think they would have implemented it so naively that it needs an extra copy.. Again the default constructor is used for the Resource object in the pair. There shouldn't be any copy-constructors invoked.
I am probably missing something here, thank you for your patience.