首页 > 解决方案 > 通过 emplace() 将对象指针插入地图地图不起作用

问题描述

我正在尝试将指针对象插入到map通过emplace()但它不起作用。

我已经为下面的问题创建了一个简单的表示。我正在尝试插入newFooList指针对象类型Foo*

我似乎找不到为FooMap*in创建类型的方法std::map<int, FooMap*> m_fooMapList。应该new在地图的第二个字段上完成吗?

#include <iostream>
#include <utility>
#include <stdint.h>
#include <cstdlib>
#include <map>

class Foo
{
    private:
        int m_foobar;
    public:
        Foo(int value)
        {
            m_foobar = value;
        }
        void setfoobar(int value);
        int getfoobar();
};

class FooMap
{
    private:
        std::map<int, Foo*> m_newFoo;

    public:
        FooMap() = default;
};

class FooMapList
{
    private:
        std::map<int, FooMap*> m_fooMapList;
    public:
        FooMapList() = default;
        void insertFoo(Foo* newFooObj);
};

int Foo::getfoobar(void)
{
    return(m_foobar);
}

void FooMapList::insertFoo(Foo* newFooObj)
{
    if(m_fooMapList.empty())
    {
        std::cout << "m_fooMapList is empty" << std::endl ;
    }

    //m_fooMapList.emplace( newFooObj->getfoobar(), newFooObj  );
    // Need to find a way to insert newFooObj  to m_fooMapList
    m_fooMapList.second = new FooMap;
}

int main() {
    FooMapList newFooList;

    for (auto i=1; i<=5; i++)
    {
        Foo *newFoo = new Foo(i);
        newFoo->getfoobar();
        newFooList.insertFoo(newFoo);
    }

    return 0;
}

在 g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28) 上

$  g++ -std=c++11 -Wall map_of_map.cpp 
map_of_map.cpp: In member function ‘void FooMapList::insertFoo(Foo*)’:
map_of_map.cpp:51:18: error: ‘class std::map<int, FooMap*>’ has no member named ‘second’
     m_fooMapList.second = new FooMap;

标签: c++c++11pointersstdmapemplace

解决方案


m_fooMapList定义为

    std::map<int, FooMap*> m_fooMapList;

所以要插入它,你需要一个int和一个指向FooMap

    m_fooMapList.emplace(newFooObj->getfoobar(), new FooMap);

话虽如此,您应该使用 C++ 值语义并减少对原始指针的依赖:

    std::map<int, FooMap> m_fooMapList; // no pointers

    m_fooMapList.emplace(newFooObj->getfoobar(), {}); // construct objects in-place

也就是说, 的实例FooMap可以直接驻留在地图本身中。

这样您可以获得更好的性能并避免内存泄漏。

unique_ptr如果您真的想使用指针,也值得研究智能指针(例如)。


推荐阅读