c++ - 通过 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;
解决方案
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
如果您真的想使用指针,也值得研究智能指针(例如)。
推荐阅读
- c# - 使用 iTextSharp 时数字签名无效
- html - 电子邮件模板的内联样式,使其像从 col-md-6 到 col-12 的引导网格
- css - 如何在样式组件中实现 CSS 混合?
- python - 请告诉我在 android 上查看 Django 网站的任何方式
- ios - 从 userNotificationCenter 的后台模式调用 Alamofire API 不起作用
- python - 将元组转换为字典列表
- database - 如何恢复单个 mongo db 文档的更新
- php - 在 foreach 循环之后在 HTML CSS 中的新页面上打印数据
- python - 选择具有外键的模型的特定实例到另一个模型
- python - Python:打开文件 - 没有这样的文件或目录