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
is a static
variable defined in a header. What this means is that every source file that includes that header gets its own copy of this variable, initialized to nullptr
. Only one source file sets its own copy to a non-null value. Presumably, some other source file in the code not shown attempts to dereference its copy.
Make it
extern Warehouse* WAREHOUSE;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.