为什么将对象分配给生成空对象的Map?

时间:2015-04-13 23:16:26

标签: c++ dictionary operator-overloading

我有以下Store课程:

class Store
{
    public:
        Store() : m_npc_id(0)
        {

        }

        Store(const int npc_id,
            vector<std::string> categories,
            vector<StoreItem> store_items) :
            m_npc_id(npc_id)
        {
            m_categories = categories;
            m_store_items = store_items;
        }

        Store& operator=(const Store& rhs)
        {
            return *this;
        }

        vector<std::string> GetCategories() const;
        vector<StoreItem> GetItems() const;
    private:
        const int m_npc_id;
        vector<std::string> m_categories;
        vector<StoreItem> m_store_items;
};

当我调用以下代码时,对象会正确存储在store变量...

const Store& store = Store(npc_id, category.second, items[npc_id]);

但是,只要我尝试将store变量插入到所有Stores的地图中,它就不起作用......存储的对象为空,并且采用Store的默认构造函数值。

for (auto &category : categories)
{
    // In this case, category.second is a string value
    // items[npc_id] is a StoreItem

    const int npc_id = category.first;

    const Store& store = Store(npc_id, category.second, items[npc_id]);
    stores[npc_id] = store;
}

1 个答案:

答案 0 :(得分:4)

您的副本分配运算符完全错误

stores[npc_id] = store;

如果在地图中找不到npc_id,地图会首先使用默认构造函数创建新的Store。然后它尝试从store复制分配。它使用以下代码进行复制:

{
    return *this;
}

鉴于您拥有const成员,您似乎有意禁止复制。在这种情况下,代码更加错误。要禁止复制,请使用Store& operator=(const Store& rhs) = delete;

你会注意到stores[npc_id] = store;不再编译。相反,你必须做一些事情来避免副本。

stores.emplace(std::piecewise_construct,
          std::forward_as_tuple(npc_id),
          std::forward_as_tuple(npc_id, category.second, items[npc_id]));

不喜欢这段代码?改为Store可复制:

class Store
{
    public:
        Store() : m_npc_id(0) {}

        Store(const int npc_id,
            vector<std::string> categories,
            vector<StoreItem> store_items) 
        :
            m_npc_id(npc_id), 
            m_categories(std::move(categories)), 
            m_store_items(std::move(store_items)), 
        {}

        const vector<std::string>& GetCategories() const;
        const vector<StoreItem>& GetItems() const;
    private:
        int m_npc_id;
        vector<std::string> m_categories;
        vector<StoreItem> m_store_items;
};

stores[npc_id] = store; //now this works!