I am using a class which uses a map underlying. When I use subscript operator in my class, I see that underlying map has values getting overridden. What am I doing wrong?
class JsonMap {
public:
ObjAndType& operator[](const string index) {
return objectMap[index];
}
private:
map<string, ObjAndType> objectMap;
};
template<typename T>
ObjAndType serialize(T data) {
ObjAndType obj;
obj.type = typeid(T).name();
obj.obj = static_cast<void*>(&data);
return obj;
}
JsonMap jsonMap;
string s1 = "firstVal", s2 = "secondVal";
jsonMap["first"] = serialize(s1);
jsonMap["second"] = serialize(s2);
cout << "printing " << *reinterpret_cast<string*>(jsonMap["first"].obj) << endl;
// prints secondVal instead of firstVal