c++ - C++ map segmentation fault (core dumped)
问题描述
I'm trying to use an map
with string
key, but it's not working and I couldn't figure out why.
I would like to have some help to understand C++ fundamentals about the usage of this so essential structure.
model.hpp
#pragma once
#include <map>
#include <utility>
#include <string>
#include <iostream>
#include "../prs/ast.h"
using namespace std;
using namespace ast;
typedef map<string, Variable> Map;
typedef pair<string, Variable> Element;
namespace model{
class Warehouse {
public:
Map stock;
Warehouse(){
Map* _stock = new Map();
stock = *_stock;
}
Variable* get(string id){
Map::iterator it = stock.find(id);
if (it != stock.end()){
return &(*it).second;
}
else {
return __define__(id);
}
}
Variable* __define__(string id){
Variable* defined = new Variable(id);
stock.insert(Element(id, *defined));
return defined;
}
};
static Warehouse* WAREHOUSE;
};
model.cpp
#pragma once
#include "model.hpp"
using namespace std;
namespace model {
Warehouse* WAREHOUSE = new Warehouse();
}
In this context,
Variable
is a project object defined inast
namespace already tested, as wellWAREHOUSE
pointer is working accordingly, with class initialized
The instruction stock.find(id)
is throwing the mentioned error message: Segmentation fault (core dumped)
, what I suppose means stock
isn't correct initialized.
What is exactly happening with stock
initialization done at Warehouse
constructor?
I understand that new
keyword alloc
s the map
and dereference its returned point would store the structure at stock
Warehouse
member attribute.
Am I misunderstand it?
解决方案
WAREHOUSE
是static
在标头中定义的变量。这意味着每个包含该头文件的源文件都会获得自己的这个变量的副本,初始化为nullptr
. 只有一个源文件将其自己的副本设置为非空值。据推测,代码中未显示的其他一些源文件试图取消引用其副本。
做了
extern Warehouse* WAREHOUSE;
推荐阅读
- syntax - ffmpeg:复制所有音频流并再添加两个
- sql-server-2012 - 如何使用 group by 和 order by 子句进行选择?
- python - python 3,打印功能如何改变输出?
- python - 如何在我的数据库中加密密码,然后立即在 Python 中解密它们?
- java - 如何从用户输入java中查找链表中的元素
- c - 漏洞利用:SIGSEGV,分段错误
- java - 无法弄清楚如何编写我的计算器
- javascript - 删除其他 DIV 时动态创建的 DIV 不保持位置
- python - 如何在python输入中添加多个元素?
- awk - 用sed中的行尾替换换行符