Search code examples
c++pointersunordered-mapuser-defined-types

Using unordered_map with dyanmically-allocated user-defined class


So I've got a class, "Room", which has the following code:

class Room
{
public:
    Room(string name, string desc): name(name), desc(desc) {}
    void operator=(const Room room)
    {
        name = room.name;
        desc = room.desc;
    }
    string getName(); //returns this.name
    string getDesc(); //returns this.desc

private:
    string name; //name of the room
    string desc; //description of the room
};

I've got a global variable in my main.cpp of type unordered_map, like this:

unordered_map<string, *Room> rooms; //Room's name is the key

And I want to allocate Rooms on the fly in a function and add them to my map. I attempted to do it like this:

void builder()
{
    Room* room = new Room("Name", "Desc");
    rooms[room->getName()] = room;
}

...But I'm getting all kinds of compiler warnings. I figured it would be something to do with iterators or hashing, or I'm not using pointers correctly (which are probably all true), but mostly it seems unordered_map doesn't like being parametrized with Room or *Room. Am I missing something?


Solution

  • There are some syntax errors as *Room. I have some tips

    #include <string>
    #include <memory>
    #include <unordered_map>
    
    using namespace std;
    
    class Room
    {
    public:
    
        Room(string name, string desc)
          : name(name) // This syntax is called initializer list 
          , desc(desc)
        {
    
        }
    
        void operator = (const Room room)
        {
            name = room.name;
            desc = room.desc;
        }
    
        string getName() { return name; }
        string getDesc() { return desc; }
    
    private:
        string name; //name of the room
        string desc; //description of the room
    };
    
    // Without using unique_ptr you have a memory leak
    // because the is not explicitly called the delete operator on pointers
    unordered_map<string, std::unique_ptr<Room> > rooms;
    
    void builder()
    { 
      Room* room = new Room("Name", "Desc");
      rooms[room->getName()].reset (room);
    }