Search code examples
c++stdmapstdstringstring-literals

What are the downsides to accessing a std::map<std::string, int> using string literals?


I have written a ResourceManager class in C++ that contains a std::map<std::string, Resource>. My current code then accesses these methods using string literals, e.g:

// ResourceManager.h
class ResourceManager {
    private:
        std::map<std::string, Resource>

    public:
        void loadResource(std::string_view resourceName, std::string_view fileName); 
        const Resource& getResource(std::string_view resourceName) const;
}

// a.cpp
resourceManager.loadResource("background image", "background_image.png")

// b.cpp
resourceManager.getResource("background image")

Is this going to be a problem? Should I replace all these string literals with constants defined in a constants.h file? In this case, should I just use an enum as the key to the map instead?


Solution

  • As with any other situation where magic constants are used, it can lead to brittle code, i.e., code that is likely to become broken. In particular, consider what happens if a "background image" resource is loaded once and retrieved from multiple different locations, possibly spanning many source files. If the resource is renamed in the loadResource call, but you forget to change one of the getResource calls, the program will have a bug. This issue can be avoided using an enum or using named constants.

    One additional benefit of having an enum as the key is that it's very efficient: any copies of the key that are made in the course of looking up the value are cheap. This stands in contrast to your current code, where you may be copying resourceName in order to perform a lookup (although this can be avoided using a transparent comparator).