Map wrapper getting values overridden

Viewed 59

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
1 Answers
obj.obj = static_cast<void*>(&data);

data is a local variable. You can't save its address like this because data's lifetime ends when the function returns. &data is only valid for the duration of the function.

If you want to store values of arbitrary types in a variable use std::any (since C++17). It holds a value and its type, exactly as you're trying to do with your ObjAndType class.

std::map<std::string, std::any> objectMap;
Related