使用带有动态分配的用户定义类的unordered_map

时间:2015-02-25 20:22:08

标签: c++ pointers unordered-map user-defined-types

所以我有一个班级," Room",它有以下代码:

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
};

我的main.cpp中有一个类型为unordered_map的全局变量,如下所示:

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

我想在一个函数中动态分配Rooms并将它们添加到我的地图中。我试图这样做:

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

...但我收到了各种编译器警告。我认为这将与迭代器或散列有关,或者我没有正确使用指针(可能都是真的),但大多数情况下看起来unordered_map并不像是使用Room或* Room进行参数化。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

*Room存在一些语法错误。我有一些提示

#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);
}