为什么将对象分配给地图会产生空对象?

Why is Assigning a Object to a Map producing an empty object?

我有以下 Store class:

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

你的复制赋值运算符完全错误

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!